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.


 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;
      cout << -1 << endl;
int main() {
   int sum = 6;
   int gcd = 2;
   printTwoNumbers(sum, gcd);


first number = 2
second number = 4