Given two values ‘a’ and ‘b’ that represent coefficients in “ax – by = 0”, find the smallest values of x and y that satisfy the equation. It may also be assumed that x > 0, y > 0, a > 0 and b > 0.
Input: a = 25, b = 35 Output: x = 7, y = 5
A Simple Solution is to try every possible value of x and y starting from 1, 1 and stop when the equation is satisfied.
A Direct Solution is to use Least Common Multiple (LCM). LCM of ‘a’ and ‘b’ represents the smallest value that can make both sides equal. We can find LCM using below formula.
LCM(a, b) = (a * b) / GCD(a, b)
Greatest Common Divisor (GCD) can be computed using Euclid’s algorithm.
x = 7 y = 5
The above code for findSmallest() can be reduced:
Since ax - by = 0, ax = by, which means x/y = b/a So we can calculate gcd and directly do as - Value of x = b / gcd; Value of y = a / gcd;
This article is contributed by Aakash Sachdeva. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Program to find whether a no is power of two
- Program to find parity
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Find Union and Intersection of two unsorted arrays
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome
- Find the element that appears once
- Find the largest multiple of 2, 3 and 5
- Program to find amount of water in a given glass
- Find the maximum distance covered using n bikes
- Find if two rectangles overlap
- Find the smallest number whose digits multiply to a given number n
- Find next greater number with same set of digits
- Find n'th number in a number system with only 3 and 4
- Find the missing number in Arithmetic Progression
- Find length of period in decimal value of 1/n
- Find number of days between two given dates
- Legendre's formula (Given p and n, find the largest x such that p^x divides n!)