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


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

Updated on: 19-Dec-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements