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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## 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.

## Example

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

## Algorithm

• 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)

## Example

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

## Output

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

Answer = 2