查找两个数字,其总和和GCD在C ++中给出
我们有两个数字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
热门推荐
10 保持快乐祝福语大全简短
11 七一祝福语明信片文案简短
12 庆祝论坛周年祝福语简短
13 祝福语同事离职英文简短
14 中秋祝福语简短版大全
15 舅舅大婚文案祝福语简短
16 小红书生日祝福语简短
17 弟弟的祝福语简短霸气
18 古风婚礼祝福语唯美简短