Minimum positive integer value possible of X for given A and B in X = P*A + Q*B in C++

Problem statement

Given values of A and B, find the minimum positive integer value of X that can be achieved in the equation X = P*A + Q*B, Here P and Q can be zero or any positive or negative integer.


If A = 2 and B = 4 then answer will be 2.


  • We need to find P and Q such that P*A > P*B and P*A – P*B is minimum positive integer.
  • This problem can be easily solved by calculating GCD of both numbers)


#include <iostream>
using namespace std;
int getGcd(int a, int b) {
   if (a == 0) {
      return b;
   return getGcd(b % a, a);
int main() {
   cout << "Answer = " << getGcd(2, 4) << endl;
   return 0;


When you compile and execute above program. It generates following output −

Answer = 2

Updated on: 22-Nov-2019


Kickstart Your Career

Get certified by completing the course

Get Started