在 C++ 中查找两个数字,它们的和与 GCD 已给出

c++server side programmingprogramming

我们有两个数字 a 和 b 的和与 gcd。我们必须找到数字 a 和 b。如果不可能,则返回 -1。假设和为 6 且 gcd 为 2,则数字为 4 和 2。

方法就像,既然 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 << "第一个数字 = " << min(g, s - g) << "\n第二个数字 = " << s - min(g, s - g) << endl;
   else
      cout << -1 << endl;
}
int main() {
   int sum = 6;
   int gcd = 2;
   printTwoNumbers(sum, gcd);
}

输出

第一个数字 = 2
第二个数字 = 4

相关文章