我们有两个数字a和b的总和和gcd。我们必须找到数字a和b。如果不可能,则返回-1。假设总和为6,gcd为2,则数字为4和2。
这种方法就像给出GCD一样,然后知道数字将是GCD的倍数。现在执行以下步骤
如果我们选择第一个数字作为GCD,则第二个数字将为和-GCD
如果在上一步中选择的数字总和与总和相同,则打印两个数字。
否则打印-1,因为不存在数字。
#include <iostream> #include <algorithm> using namespace std; void printTwoNumbers(int s, int g) { if (__gcd(g, s - g) == g && s != g) cout << "first number = " << min(g, s - g) << "\nsecond number = " << s - min(g, s - g) << endl; else cout << -1 << endl; } int main() { int sum = 6; int gcd = 2; printTwoNumbers(sum, gcd); }
输出结果
first number = 2 second number = 4