VOOZH about

URL: https://www.geeksforgeeks.org/dsa/linear-diophantine-equations/

⇱ Linear Diophantine Equations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Linear Diophantine Equations

Last Updated : 1 Apr, 2026

Given three integers a, b and c, determine whether there exist integers x and y that satisfy the Linear Diophantine equation.

Note: A Linear Diophantine Equation is of the form ax + by = c, where integer solutions for x and y are checked.

Examples:

Input: a = 3, b = 6, c = 9
Output: true
Explanation: The Equation is 3x + 6y = 9, one integral solution would be x = 1 , y = 1

Input: a = 3, b = 6, c = 8
Output: false
Explanation: No integral values of x and y exists that can satisfy the equation 3x + 6y = 8

Input: a = 2, b = 5, c = 1
Output: true
Explanation: Various integral solutions possible are, (-2,1) , (3,-1) etc.

Diophantine equation has a solution if and only if the greatest common divisor of a and b divides c. Let g = gcd(a, b), then if c % g == 0, a solution exists otherwise no solution exists.

Why does this solution work?

Let GCD of 'a' and 'b' be 'g'. g divides a and b. This implies g also divides (ax + by) (if x and y are integers). This implies gcd also divides 'c' using the relation that ax + by = c.


Output
true
false
true

Time Complexity: The program’s complexity is dominated by the GCD computation, which uses the Euclidean algorithm. The Euclidean algorithm runs in O(log min(a, b)) time. Since the isPossible function calls gcd only once, its time complexity is also O(log min(a, b)).

Auxiliary Space : The program uses a fixed number of variables (a, b, c, gcd, and a few booleans/strings). These do not depend on input size, so the auxiliary space is O(1) (constant).

Comment
Article Tags:
Article Tags: