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 email@example.com. 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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find N values of X1, X2, ... Xn such that X1 < X2 < ... < XN and sin(X1) < sin(X2) < ... < sin(XN)
- Find the values of X and Y in the Given Equations
- Find minimum possible values of A, B and C when two of the (A + B), (A + C) and (B + C) are given
- Find minimum value of y for the given x values in Q queries from all the given set of lines
- Find the minimum value of m that satisfies ax + by = m and all values after m also satisfy
- Find Kth smallest value for b such that a + b = a | b
- Find the original Array using XOR values of all adjacent elements
- Program to find the XOR of ASCII values of characters in a string
- Find K'th smallest number such that A + B = A | B
- Find smallest number K such that K % p = 0 and q % K = 0
- Find the sum of the ascii values of characters which are present at prime positions
- Find the Smallest number that divides X^X
- Find smallest number n such that n XOR n+1 equals to given k.
- Given a number, find the next smallest palindrome
- Find smallest permutation of given number