The Wayback Machine - https://web.archive.org/web/20240527032140/https://www.geeksforgeeks.org/linear-diophantine-equations/
Open In App

Linear Diophantine Equations

Last Updated : 17 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A Diophantine equation is a polynomial equation, usually in two or more unknowns, such that only the integral solutions are required. An Integral solution is a solution such that all the unknown variables take only integer values.

Given three integers a, b, c representing a linear equation of the form : ax + by = c. Determine if the equation has a solution such that x and y are both integral values.

Examples:  

Input : a = 3, b = 6, c = 9
Output: Possible
Explanation : The Equation turns out to be,
3x + 6y = 9 one integral solution would be
x = 1 , y = 1
Input : a = 3, b = 6, c = 8
Output : Not Possible
Explanation : o integral values of x and y
exists that can satisfy the equation 3x + 6y = 8
Input : a = 2, b = 5, c = 1
Output : Possible
Explanation : Various integral solutions
possible are, (-2,1) , (3,-1) etc.
Recommended Practice

Solution: 

For linear Diophantine equation equations, integral solutions exist if and only if, the GCD of coefficients of the two variables divides the constant term perfectly. In other words, the integral solution exists if, GCD(a ,b) divides c.
Thus the algorithm to determine if an equation has integral solution is pretty straightforward. 

  • Find GCD of a and b
  • Check if c % GCD(a ,b) ==0
  • If yes then print Possible
  • Else print Not Possible

Below is the implementation of the above approach.  

C++




// C++ program to check for solutions of diophantine
// equations
#include <bits/stdc++.h>
using namespace std;
 
//utility function to find the GCD of two numbers
int gcd(int a, int b)
{
    return (a%b == 0)? abs(b) : gcd(b,a%b);
}
 
// This function checks if integral solutions are
// possible
bool isPossible(int a, int b, int c)
{
    return (c%gcd(a,b) == 0);
}
 
//driver function
int main()
{
    // First example
    int a = 3, b = 6, c = 9;
    isPossible(a, b, c)? cout << "Possible\n" :
                        cout << "Not Possible\n";
 
    // Second example
    a = 3, b = 6, c = 8;
    isPossible(a, b, c)? cout << "Possible\n" :
                       cout << "Not Possible\n";
 
    // Third example
    a = 2, b = 5, c = 1;
    isPossible(a, b, c)? cout << "Possible\n" :
                       cout << "Not Possible\n";
 
    return 0;
}


Java




// Java program to check for solutions of
// diophantine equations
import java.io.*;
 
class GFG {
     
    // Utility function to find the GCD
    // of two numbers
    static int gcd(int a, int b)
    {
        return (a % b == 0) ?
                Math.abs(b) : gcd(b,a%b);
    }
     
    // This function checks if integral
    // solutions are possible
    static boolean isPossible(int a,
                            int b, int c)
    {
        return (c % gcd(a, b) == 0);
    }
     
    // Driver function
    public static void main (String[] args)
    {
        // First example
        int a = 3, b = 6, c = 9;
        if(isPossible(a, b, c))
            System.out.println( "Possible" );
        else
            System.out.println( "Not Possible");
     
        // Second example
        a = 3; b = 6; c = 8;
        if(isPossible(a, b, c))
            System.out.println( "Possible") ;
        else
            System.out.println( "Not Possible");
     
        // Third example
        a = 2; b = 5; c = 1;
        if(isPossible(a, b, c))
            System.out.println( "Possible" );
        else
            System.out.println( "Not Possible");
    }
}
 
// This code is contributed by anuj_67.


Python3




# Python 3 program to check for solutions
# of diophantine equations
from math import gcd
 
# This function checks if integral
# solutions are possible
def isPossible(a, b, c):
    return (c % gcd(a, b) == 0)
 
# Driver Code
if __name__ == '__main__':
     
    # First example
    a = 3
    b = 6
    c = 9
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")
 
    # Second example
    a = 3
    b = 6
    c = 8
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")
 
    # Third example
    a = 2
    b = 5
    c = 1
    if (isPossible(a, b, c)):
        print("Possible")
    else:
        print("Not Possible")
         
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to check for
// solutions of diophantine
// equations
using System;
 
class GFG
{
     
    // Utility function to find
    // the GCD of two numbers
    static int gcd(int a, int b)
    {
        return (a % b == 0) ?
                Math.Abs(b) :
               gcd(b, a % b);
    }
     
    // This function checks
    // if integral solutions
    // are possible
    static bool isPossible(int a,
                           int b,
                           int c)
    {
        return (c % gcd(a, b) == 0);
    }
     
    // Driver Code
    public static void Main ()
    {
        // First example
        int a = 3, b = 6, c = 9;
        if(isPossible(a, b, c))
            Console.WriteLine("Possible");
        else
            Console.WriteLine("Not Possible");
     
        // Second example
        a = 3; b = 6; c = 8;
        if(isPossible(a, b, c))
            Console.WriteLine("Possible") ;
        else
            Console.WriteLine("Not Possible");
     
        // Third example
        a = 2; b = 5; c = 1;
        if(isPossible(a, b, c))
            Console.WriteLine("Possible");
        else
            Console.WriteLine("Not Possible");
    }
}
 
// This code is contributed by anuj_67.


Javascript




<script>
 
// Javascript program to check for solutions of
// diophantine equations
 
    // Utility function to find the GCD
    // of two numbers
    function gcd(a, b)
    {
        return (a % b == 0) ?
                Math.abs(b) : gcd(b,a%b);
    }
       
    // This function checks if integral
    // solutions are possible
    function isPossible(a,
                            b, c)
    {
        return (c % gcd(a, b) == 0);
    }
   
 
// Driver Code
 
        // First example
        let a = 3, b = 6, c = 9;
        if(isPossible(a, b, c))
           document.write( "Possible" + "<br/>" );
        else
           document.write( "Not Possible" + "<br/>" );
       
        // Second example
        a = 3; b = 6; c = 8;
        if(isPossible(a, b, c))
           document.write( "Possible" + "<br/>" ) ;
        else
           document.write( "Not Possible" + "<br/>" );
       
        // Third example
        a = 2; b = 5; c = 1;
        if(isPossible(a, b, c))
           document.write( "Possible" + "<br/>" );
        else
           document.write( "Not Possible" + "<br/>" );
                       
</script>


PHP




<?php
// PHP program to check for solutions of
// diophantine equations
 
// utility function to find the
// GCD of two numbers
function gcd($a, $b)
{
    return ($a % $b == 0) ?
                  abs($b) : gcd($b, $a % $b);
}
 
// This function checks if integral
// solutions are possible
function isPossible($a, $b, $c)
{
    return ($c % gcd($a, $b) == 0);
}
 
// Driver Code
 
// First example
$a = 3;
$b = 6;
$c = 9;
if(isPossible($a, $b, $c) == true)
    echo "Possible\n" ;
else
    echo "Not Possible\n";
 
// Second example
$a = 3;
$b = 6;
$c = 8;
 
if(isPossible($a, $b, $c) == true)
    echo "Possible\n" ;
else
    echo "Not Possible\n";
 
// Third example
$a = 2;
$b = 5;
$c = 1;
if(isPossible($a, $b, $c) == true)
    echo "Possible\n" ;
else
    echo "Not Possible\n";
 
// This code is contributed by ajit..
?>


Output : 

Possible
Not Possible
Possible

Time Complexity: O(min(a,b))

Auxiliary Space: O(1)

How does this 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. Refer this wiki link for more details.

New Approach:-

1. Find GCD of a and b using Euclidean algorithm:

  • Divide the larger number by the smaller number and find the remainder.
  • Repeat the process with the divisor (smaller number) and the remainder.
  • Continue this process until the remainder becomes zero.
  • The GCD will be the last non-zero remainder.

2. Check if c is divisible by GCD(a, b).

  • If c is divisible by GCD(a, b), then there exist integer solutions.
  • Otherwise, there are no integer solutions.

Below is the implementation of the above approach:-

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the GCD of two numbers
int gcd(int a, int b)
{
    if (a == 0) {
        return b;
    }
    return gcd(b % a, a);
}
 
// Function to check if integral solutions are possible
bool isPossible(int a, int b, int c)
{
    int gcd_val = gcd(a, b);
    return (c % gcd_val == 0);
}
 
// Driver function
int main()
{
    int a = 3, b = 6, c = 9;
    if (isPossible(a, b, c)) {
        cout << "Possible" << endl;
    }
    else {
        cout << "Not Possible" << endl;
    }
    return 0;
}


Java




import java.util.*;
 
class LinearDiophantineEquations {
     
    // Function to find the GCD of two numbers
    public static int gcd(int a, int b) {
        if (a == 0) {
            return b;
        }
        return gcd(b % a, a);
    }
     
    // Function to check if integral solutions are possible
    public static boolean isPossible(int a, int b, int c) {
        int gcd = gcd(a, b);
        return (c % gcd == 0);
    }
     
    // Driver function
    public static void main(String[] args) {
        int a = 3, b = 6, c = 9;
        if (isPossible(a, b, c)) {
            System.out.println("Possible");
        } else {
            System.out.println("Not Possible");
        }
    }
}


Python3




class LinearDiophantineEquations:
     
    # Function to find the GCD of two numbers
    def gcd(self, a, b):
        if a == 0:
            return b
        return self.gcd(b % a, a)
     
    # Function to check if integral solutions are possible
    def isPossible(self, a, b, c):
        gcd = self.gcd(a, b)
        return c % gcd == 0
     
    # Driver function
    def main(self):
        a, b, c = 3, 6, 9
        if self.isPossible(a, b, c):
            print("Possible")
        else:
            print("Not Possible")
         
# Create an object of the class and call the main function
ld = LinearDiophantineEquations()
ld.main()


C#




using System;
 
class GFG
{
    // Function to find the GCD of two numbers
    static int GCD(int a, int b)
    {
        if (a == 0)
        {
            return b;
        }
        return GCD(b % a, a);
    }
 
    // Function to check if integral solutions are possible
    static bool IsPossible(int a, int b, int c)
    {
        int gcdVal = GCD(a, b);
        return (c % gcdVal == 0);
    }
 
    // Driver function
    static void Main(string[] args)
    {
        int a = 3, b = 6, c = 9;
        if (IsPossible(a, b, c))
        {
            Console.WriteLine("Possible");
        }
        else
        {
            Console.WriteLine("Not Possible");
        }
    }
}


Javascript




    // Function to find the GCD of two numbers
    function gcd(a, b) {
    if (a === 0) {
        return b;
    }
    return gcd(b % a, a);
}
 
// Function to check if integral solutions are possible
function isPossible(a, b, c) {
    let gcdValue = gcd(a, b);
    return (c % gcdValue === 0);
}
 
 // Driver function
let a = 3,
    b = 6,
    c = 9;
if (isPossible(a, b, c)) {
    console.log("Possible");
} else {
    console.log("Not Possible");
}


Output:-

Possible

Time Complexity:-The time complexity of this program is dominated by the gcd function, which uses the Euclidean algorithm to compute the GCD of two numbers. The time complexity of the Euclidean algorithm is O(log min(a, b)), so the time complexity of the gcd function is O(log min(a, b)). Since the isPossible function calls the gcd function once, its time complexity is also O(log min(a, b)).

Auxiliary Space:-The space complexity of this program is O(1), since we are only using a few integer variables (a, b, c, and gcd) and a few boolean and string variables (isPossible and the output string). None of these variables grow with the input size, so the space complexity is constant.

Therefore, the time complexity of this program is O(log min(a, b)) and the space complexity is O(1).

 



Similar Reads

Find initial integral solution of Linear Diophantine equation if finite solution exists
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 a 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
8 min read
System of Linear Equations in three variables using Cramer's Rule
Cramer's rule: In linear algebra, Cramer's rule is an explicit formula for the solution of a system of linear equations with as many equations as unknown variables. It expresses the solution in terms of the determinants of the coefficient matrix and of matrices obtained from it by replacing one column by the column vector of the right-hand-sides of
12 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.5 | Set 2
Question 14. Find the value of k for which each of the following system of equations having infinitely many solutions: 2x + 3y = 2,(k + 2)x + (2k + 1)y = 2(k − 1) Solution: Given that, 2x + 3y = 2 ...(1) (k + 2)x + (2k + 1)y = 2(k − 1) ...(2) So, the given equations are in the form of: a1x + b1y − c1 = 0 ...(3) a2x + b2y − c2 = 0 ...(4) On comparin
12 min read
Data Science - Solving Linear Equations with Python
A collection of equations with linear relationships between the variables is known as a system of linear equations. The objective is to identify the values of the variables that concurrently satisfy each equation, each of which is a linear constraint. By figuring out the system, we can learn how the variables interact and find hidden relationships
4 min read
Forms of Two-Variable Linear Equations - Straight Lines | Class 11 Maths
Line is the simplest geometrical shape. It has no endpoints and extends in both directions till infinity. The word “straight” simply means without “bend”. The gradient between any two point on the line is same. Hence, we can say that, if the gradient between any two points on the line is same, then the locus is a straight line. So let's see what ar
5 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.11 | Set 1
Question 1. If in a rectangle, the length is increased and breadth reduced each by 2 units, the area is reduced by 28 square units. If, however the length is reduced by 1 unit and the breadth increased by 2 units, the area increases by 33 square units. Find the area of the rectangle. Solution: Let’s assume the length and breadth of the rectangle be
15 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.11 | Set 2
Question 13. A part of monthly hostel charges in a college are fixed and the remaining depend on the number of days one has taken food in the mess. When a student A takes food for 20 days, he has to pay ₹ 1000 as hostel charges whereas a student B, who takes food for 26 days, pays ₹ 1180 as hostel charges. Find the fixed charged and the cost of foo
11 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.5 | Set 1
Question 1. In each of the following systems of equation determine whether the system has a unique solution, no solution, or infinite solutions. In case there is a unique solution:x − 3y − 3 = 0, 3x − 9y − 2 = 0 Solution: Given that, x − 3y − 3 = 0 ...(1) 3x − 9y − 2 = 0 ...(2) So, the given equations are in the form of: a1x + b1y − c1 = 0 ...(3) a
10 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.5 | Set 3
Question 27. For what value of a, the following system of the equation has no solution:ax + 3y = a − 312x + ay = a Solution: Given that, ax + 3y = a − 3 ...(1) 12x + ay = a ...(2) So, the given equations are in the form of: a1x + b1y − c1 = 0 ...(3) a2x + b2y − c2 = 0 ...(4) On comparing eq (1) with eq(3) and eq(2) with eq (4), we get a1 = a, b1 =
18 min read
Class 10 RD Sharma Solutions - Chapter 3 Pair of Linear Equations in Two Variables - Exercise 3.8
Question 1. The numerator of a fraction is 4 less than the denominator. If the numerator is decreased by 2 and denominator is increased by 1, then the denominator is eight times the numerator. Find the fraction. Solution: Let's assume that the numerator and denominator of the fraction be x and y respectively. Therefore, the fraction is x/y Accordin
9 min read
Article Tags :
Practice Tags :