查找两个数字,其总和和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 婆婆高寿祝福语大全简短