Given three integers a, b and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if finite solution exists.
A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine equation in two variables takes the form of ax+by=c, where x,y are integer variables and a, b, c are integer constants. x and y are unknown variables.
Input: a = 4, b = 18, c = 10
Output: x = -20, y = 5
Explanation: (-20)*4 + (5)*18 = 10
Input: a = 9, b = 12, c = 5
Output: No Solutions exists
- First check if a and are non-zero.
- If both of them are zero and c is non-zero then, no solution exists. If c is also zero then infinite solution exits.
- For given a and b, calculate value of x1, y1 and gcd using Extended Euclidean Algorithm.
- Now, for solution to exist gcd(a, b) should be multiple of c.
- Calculate solution of the equation as follows:
x = x1 * ( c / gcd ) y = y1 * ( c / gcd )
Below is the implementation of the above approach:
x = -20, y = 5
Time Complexity: O(log(max(A, B))), where A and B are the coefficient of x and y in the given linear equation.
Auxiliary Space: O(1)
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.
- Probability that an arbitrary positive divisor of 10^X is an integral multiple of 10^Y
- Satisfy the parabola when point (A, B) and the equation is given
- Find the first natural number whose factorial is divisible by x
- Find maximum array sum after making all elements same with repeated subtraction
- Find an Integer point on a line segment with given two ends
- Program to find GCD or HCF of two numbers
- Program to find LCM of two numbers
- Given GCD G and LCM L, find number of possible pairs (a, b)
- Program to find HCF iteratively
- Find pair with maximum GCD in an array
- Program to find GCD of floating point numbers
- Find element in array that divides all array elements
- Find max of two Rational numbers
- Find LCM of rational numbers
- Find the GCD that lies in given range
- Program to find LCM of 2 numbers without using GCD
- Find unique pairs such that each element is less than or equal to N
- Find three integers less than or equal to N such that their LCM is maximum
- Find gcd(a^n, c) where a, n and c can vary from 1 to 10^9
- Program to find HCF (Highest Common Factor) of 2 Numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.