Find two numbers whose sum and GCD are given in C++


We have the sum and gcd of two numbers a and b. We have to find both numbers a and b. If that is not possible, return -1. Suppose the sum is 6 and gcd is 2, then the numbers are 4 and 2.

The approach is like, as the GCD is given, then it is known that the numbers will be multiples of it. Now there following steps

  • If we choose the first number as GCD, then the second one will be sum − GCD

  • If the sum of the numbers is chosen in the previous step is the same as the sum, then print both numbers.

  • Otherwise print -1, as a number does not exist.

Example

 Live Demo

#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);
}

Output

first number = 2
second number = 4

Updated on: 21-Oct-2019

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements