Find smallest values of x and y such that ax – by = 0 in C++

C++Server Side ProgrammingProgramming

Suppose we have two values a and b. We have to find x and y, such that ax – by = 0. So if a = 25 and b = 35, then x = 7 and y = 5.

To solve this, we have to calculate the LCM of a and b. LCM of a and b will be the smallest value that can make both sides equal. The LCM can be found using GCD of numbers using this formula −

LCM (a,b)=(a*b)/GCD(a,b)

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
void getSmallestXY(int a, int b) {
   int lcm = (a * b) / __gcd(a, b);
   cout << "x = " << lcm / a << "\ny = " << lcm / b;
}
int main() {
   int a = 12, b = 26;
   getSmallestXY(a, b);
}

Output

x = 13
y = 6
raja
Published on 19-Dec-2019 12:08:25
Advertisements