Skip to content
Related Articles
Open in App
Not now

Related Articles

Program to Find GCD or HCF of Two Numbers

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 14 Mar, 2023
Improve Article
Save Article

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. 

For example, GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14. 

A simple and old  approach is the Euclidean algorithm by subtraction

 It is a process of repeat subtraction, carrying the result forward each time until the result is equal to any one number being subtracted. If the answer is greater than 1, there is a GCD (besides 1). If the answer is 1, there is no common divisor (besides 1), and so both numbers are coprime

pseudo code for the above approach:

def gcd(a, b):
  if a == b:
    return a
  if a > b:
    gcd(a – b, b)
  else:
    gcd(a, b – a)

At some point, one number becomes factor of the other so instead of repeatedly subtracting till both become equal, we check if it is factor of the other.  

For Example, suppose a=98 & b=56  a>b so put a= a-b and b remains same. So  a=98-56=42  & b= 56 . Since b>a, we check if b%a==0. since answer is no we proceed further. Now b>a  so  b=b-a and a remain same. So b= 56-42 = 14 & a= 42   . Since a>b, we check if a%b==0 . Now the answer is yes. So we print smaller among a and b as H.C.F . i.e. 42 is  3 times of 14  so HCF is 14. 

likewise  when a=36  & b=60  ,here b>a  so b = 24 & a= 36 but a%b!=0.  Now a>b so a= 12 & b= 24  . and b%a==0. smaller among a and b is 12  which becomes  HCF of 36 and 60.   

Simple Solution :

Approach: For finding the GCD of two numbers we will first find the minimum of the two numbers and then find the highest common factor of that minimum which is also the factor of the other number.

C++




// C++ program to find GCD of two numbers
#include <iostream>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
    int result = min(a, b); // Find Minimum of a and b
    while (result > 0) {
        if (a % result == 0 && b % result == 0) {
            break;
        }
        result--;
    }
    return result; // return gcd of a and b
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    cout << "GCD of " << a << " and " << b << " is "
         << gcd(a, b);
    return 0;
}
// This code is contributed by Suruchi Kumari

C




// C program to find GCD of two numbers
#include <math.h>
#include <stdio.h>
 
// Function to return gcd of a and b
int gcd(int a, int b)
{
    // Find Minimum of a and b
    int result = ((a < b) ? a : b);
    while (result > 0) {
        if (a % result == 0 && b % result == 0) {
            break;
        }
        result--;
    }
    return result; // return gcd of a and b
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}
// This code is contributed by Suruchi Kumari

Java




// Java program to find GCD of two numbers
import java.io.*;
 
public class GFG {
     
    // Function to return gcd of a and b
    static int gcd(int a, int b)
    {
        int result = Math.min(a, b); // Find Minimum of a and b
        while (result > 0) {
            if (a % result == 0 && b % result == 0) {
                break;
            }
            result--;
        }
        return result; // return gcd of a and b
    }
     
    // Driver program to test above function
    public static void main (String[] args)
    {
        int a = 98, b = 56;
        System.out.print("GCD of " + a + " and " + b + " is " + gcd(a, b));
    }
}
 
// This code is contributed by AnkThon

Python3




# Python program to find GCD of two numbers
 
# Function to find gcd of two numbers
 
 
def gcd(a, b):
    # Find minimum of a and b
    result = min(a, b)
 
    while result:
        if a % result == 0 and b % result == 0:
            break
        result -= 1
 
    # Return the gcd of a and b
    return result
 
 
# Driver Code
a = 98
b = 56
 
print(f"GCD of {a} and {b} is {gcd(a, b)}")
 
# This code is contributed by Soham Mirikar

C#




// C# program to find GCD of two numbers
using System;
public class GFG
{
 
  // Function to return gcd of a and b
  static int gcd(int a, int b)
  {
    int result = Math.Min(a, b); // Find Minimum of a and b
    while (result > 0) {
      if (a % result == 0 && b % result == 0) {
        break;
      }
      result--;
    }
    return result; // return gcd of a and b
  }
 
  // Driver program to test above function
  public static void Main (string[] args)
  {
    int a = 98, b = 56;
    Console.WriteLine("GCD of " + a + " and " + b + " is " + gcd(a, b));
  }
}
 
// This code is contributed by AnkThon

Javascript




<script>
// Javascript program to find GCD of two numbers
// Function to return gcd of a and b
function gcd(a,b)
{
    let result = Math.min(a, b); // Find Minimum of a and b
    while (result > 0) {
        if (a % result == 0 && b % result == 0) {
            break;
        }
        result--;
    }
    return result; // return gcd of a and b
}
 
// Driver program to test above function
let a = 98;
let b = 56;
console.log("GCD of ",a," and ",b," is ",gcd(a, b));
// This code is contributed by akashish__
</script>

Output

GCD of 98 and 56 is 14

Time Complexity : O(min(a,b)) 
Auxiliary Space: O(1)

An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if a smaller number is subtracted from a bigger number. 

C++




// C++ program to find GCD of two numbers
#include <iostream>
using namespace std;
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0
    if (a == 0)
       return b;
    if (b == 0)
       return a;
  
    // base case
    if (a == b)
        return a;
  
    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}
  
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b);
    return 0;
}

C




// C program to find GCD of two numbers
#include <stdio.h>
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0
    if (a == 0)
       return b;
    if (b == 0)
       return a;
 
    // base case
    if (a == b)
        return a;
 
    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}

Java




// Java program to find GCD of two numbers
import java.io.*;
 
class Test
{
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;
      
        // base case
        if (a == b)
            return a;
      
        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }
     
    // Driver method
    public static void main(String[] args)
    {
        int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}

Python3




# Recursive function to return gcd of a and b
def gcd(a, b):
 
    # Everything divides 0
    if (a == 0):
        return b
    if (b == 0):
        return a
 
    # base case
    if (a == b):
        return a
 
    # a is greater
    if (a > b):
        return gcd(a-b, b)
    return gcd(a, b-a)
 
 
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')
 
# This code is contributed by Danish Raza

C#




// C# program to find GCD of two
// numbers
using System;
 
class GFG {
     
    // Recursive function to return
    // gcd of a and b
    static int gcd(int a, int b)
    {
         
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;
     
        // base case
        if (a == b)
            return a;
     
        // a is greater
        if (a > b)
            return gcd(a - b, b);
             
        return gcd(a, b - a);
    }
     
    // Driver method
    public static void Main()
    {
        int a = 98, b = 56;
        Console.WriteLine("GCD of "
          + a +" and " + b + " is "
                      + gcd(a, b));
    }
}
 
// This code is contributed by anuj_67.

PHP




<?php
// PHP program to find GCD
// of two numbers
 
// Recursive function to
// return gcd of a and b
function gcd($a, $b)
{
 
    // Everything divides 0
    if ($a == 0)
       return $b;
    if ($b == 0)
       return $a;
 
    // base case
    if($a == $b)
        return $a ;
     
    // a is greater
    if($a > $b)
        return gcd( $a-$b , $b ) ;
 
    return gcd( $a , $b-$a ) ;
}
 
// Driver code
$a = 98 ;
$b = 56 ;
 
echo "GCD of $a and $b is ", gcd($a , $b) ;
 
// This code is contributed by Anivesh Tiwari
?>

Javascript




<script>
 
// Javascript program to find GCD of two numbers
 
// Recursive function to return gcd of a and b
function gcd(a, b)
{
    // Everything divides 0
    if (a == 0)
    return b;
    if (b == 0)
    return a;
 
    // base case
    if (a == b)
        return a;
 
    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}
 
// Driver program to test above function
 
    let a = 98, b = 56;
    document.write("GCD of "+ a + " and " + b + " is " + gcd(a, b));
     
// This code is contributed by Mayank Tyagi
 
</script>

Output

GCD of 98 and 56 is 14

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

Approach (Top Down Using Memoization) :

C++




// C++ program to find GCD of two numbers
#include <bits/stdc++.h>
using namespace std;
 
int static dp[1001][1001];
 
// Function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0
    if (a == 0)
        return b;
    if (b == 0)
        return a;
 
    // base case
    if (a == b)
        return a;
     
    // if a value is already
    // present in dp
    if(dp[a][b] != -1)
        return dp[a][b];
 
    // a is greater
    if (a > b)
        dp[a][b] = gcd(a-b, b);
     
    // b is greater
    else
        dp[a][b] = gcd(a, b-a);
     
    // return dp
    return dp[a][b];
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    memset(dp, -1, sizeof(dp));
    cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b);
    return 0;
}

Java




// Java program to find GCD of two numbers
import java.util.*;
import java.io.*;
 
public class GFG
{
    static int [][]dp = new int[1001][1001];
   
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
       
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;
      
        // base case
        if (a == b)
            return a;
      
        // if a value is already
    // present in dp
    if(dp[a][b] != -1)
        return dp[a][b];
 
    // a is greater
    if (a > b)
        dp[a][b] = gcd(a-b, b);
     
    // b is greater
    else
        dp[a][b] = gcd(a, b-a);
     
    // return dp
    return dp[a][b];
    }
     
    // Driver method
    public static void main(String[] args)
    {
        for(int i = 0; i < 1001; i++) {
            for(int j = 0; j < 1001; j++) {
                dp[i][j] = -1;
            }
        }
        int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3




# function to return gcd of a and b
 
# Taking the matrix as globally
dp = [[-1 for i in range(1001)] for j in range(1001)]
 
def gcd(a,b):
     
    # Everything divides 0
    if (a == 0):
        return b
    if (b == 0):
        return a
 
    # base case
    if (a == b):
        return a
     
    if(dp[a][b] != -1):
        return dp[a][b]
         
    # a is greater
    if (a > b):
        dp[a][b] = gcd(a-b, b)
    else:
        dp[a][b] = gcd(a, b-a)
         
    return dp[a][b]
 
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')
 
# This code is contributed by Samim Hossain Mondal.

C#




// C# program to find GCD of two numbers
using System;
class GFG
{
    static int [,]dp = new int[1001, 1001];
   
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
       
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;
      
        // base case
        if (a == b)
            return a;
      
    // if a value is already
    // present in dp
    if(dp[a, b] != -1)
        return dp[a, b];
 
    // a is greater
    if (a > b)
        dp[a, b] = gcd(a-b, b);
     
    // b is greater
    else
        dp[a, b] = gcd(a, b-a);
     
    // return dp
    return dp[a, b];
    }
     
    // Driver method
    public static void Main()
    {
        for(int i = 0; i < 1001; i++) {
            for(int j = 0; j < 1001; j++) {
                dp[i, j] = -1;
            }
        }
        int a = 98, b = 56;
        Console.Write("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




//<script>
// Javascript program to find GCD of two numbers
var dp = new Array(1001);
 
// Loop to create 2D array using 1D array
for (var i = 0; i < dp.length; i++) {
    dp[i] = new Array(1001);
}
 
// Function to return gcd of a and b
function gcd(a, b)
{
 
    // Everything divides 0
    if (a == 0)
        return b;
    if (b == 0)
        return a;
 
    // base case
    if (a == b)
        return a;
     
    // if a value is already
    // present in dp
    if(dp[a][b] != -1)
        return dp[a][b];
 
    // a is greater
    if (a > b)
        dp[a][b] = gcd(a-b, b);
     
    // b is greater
    else
        dp[a][b] = gcd(a, b-a);
     
    // return dp
    return dp[a][b];
}
 
// Driver program to test above function
    let a = 98, b = 56;
     
    for(let i = 0; i < 1001; i++) {
        for(let j = 0; j < 1001; j++) {
            dp[i][j] = -1;
        }
    }
    document.write("GCD of "+ a + " and " + b + " is " + gcd(a, b));
     
// This code is contributed by Samim Hossain Mondal
 
</script>

Output

GCD of 98 and 56 is 14

Time Complexity: O(min(a,b))
Auxiliary Space: O(1)

Instead of the Euclidean algorithm by subtraction, a better approach is present. We don’t perform subtraction here. we continuously divide the bigger number by the smaller number. More can be learned about this efficient solution by using modulo operator in Euclidean algorithm.

C++




// C++ program to find GCD of two numbers
#include <iostream>
using namespace std;
// Recursive function to return gcd of a and b in single line
int gcd(int a, int b)
{
    return b == 0 ? a : gcd(b, a % b);   
}
  
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b);
    return 0;
}

C




// C program to find GCD of two numbers
#include <stdio.h>
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}

Java




// Java program to find GCD of two numbers
import java.io.*;
 
class Test
{
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
      if (b == 0)
        return a;
      return gcd(b, a % b);
    }
     
    // Driver method
    public static void main(String[] args)
    {
        int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}

Python3




# Recursive function to return gcd of a and b
def gcd(a,b):
     
    # Everything divides 0
    if (b == 0):
         return a
    return gcd(b, a%b)
 
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')
 
# This code is contributed by Danish Raza

C#




// C# program to find GCD of two
// numbers
using System;
 
class GFG {
     
    // Recursive function to return
    // gcd of a and b
    static int gcd(int a, int b)
    {     
       if (b == 0)
          return a;
       return gcd(b, a % b);
    }
     
    // Driver method
    public static void Main()
    {
        int a = 98, b = 56;
        Console.WriteLine("GCD of "
          + a +" and " + b + " is "
                      + gcd(a, b));
    }
}
 
// This code is contributed by anuj_67.

PHP




<?php
// PHP program to find GCD
// of two numbers
 
// Recursive function to
// return gcd of a and b
function gcd($a, $b)
{
    // Everything divides 0
    if($b==0)
        return $a ;
 
    return gcd( $b , $a % $b ) ;
}
 
// Driver code
$a = 98 ;
$b = 56 ;
 
echo "GCD of $a and $b is ", gcd($a , $b) ;
 
// This code is contributed by Anivesh Tiwari
?>

Javascript




<script>
 
// Javascript program to find GCD of two number
 
// Recursive function to return gcd of a and b
 
function gcd(a, b){
   
  // Everything divides 0
  if(b == 0){
    return a;
  }
   
  return gcd(b, a % b);
}
 
// Driver code
let a = 98;
let b = 56;
 
document.write(`GCD of ${a} and ${b} is ${gcd(a, b)}`);
 
// This code is contributed by _saurabh_jaiswal
 
</script>

Output

GCD of 98 and 56 is 14

Time Complexity: O(log(min(a,b))|
Auxiliary Space: O(log(min(a,b))

The time complexity for the above algorithm is O(log(min(a,b))) the derivation for this is obtained from the analysis of the worst-case scenario. What we do is we ask what are the 2 least numbers that take 1 step, those would be (1,1). If we want to increase the number of steps to 2 while keeping the numbers as low as possible as we can take the numbers to be (1,2). Similarly, for 3 steps, the numbers would be (2,3), 4 would be (3,5), 5 would be (5,8). So we can notice a pattern here, for the nth step the numbers would be (fib(n), fib(n+1)).  So the worst-case time complexity would be O(n) where a>= fib(n) and b>= fib(n+1). 

Now Fibonacci series is an exponentially growing series where the ratio of nth/(n-1)th term approaches (sqrt(5)+1)/2 which is also called the golden ratio. So we can see that the time complexity of the algorithm increases linearly as the terms grow exponentially hence the time complexity would be log(min(a,b)).

Iterative Code for GCD of 2 numbers using Euclidean Algorithm

C++




// C++ program to find GCD of two numbers
#include <iostream>
using namespace std;
 
// Iterative function to return gcd of a and b
int gcd(int a, int b)
{
    while (a > 0 && b > 0) {
        if (a > b) {
            a = a % b;
        }
        else {
            b = b % a;
        }
    }
    if (a == 0) {
        return b;
    }
    return a;
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    cout << "GCD of " << a << " and " << b << " is "
         << gcd(a, b);
    return 0;
}

C




// C program to find GCD of two numbers
#include <stdio.h>
 
// Iterative function to return gcd of a and b
int gcd(int a, int b)
{
    while (a > 0 && b > 0) {
        if (a > b) {
            a = a % b;
        }
        else {
            b = b % a;
        }
    }
    if (a == 0) {
        return b;
    }
    return a;
}
 
// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}

Java




// Java program to find GCD of two numbers
import java.io.*;
 
class Test {
    // Iterative function to return gcd of a and b
    static int gcd(int a, int b)
    {
        while (a > 0 && b > 0) {
            if (a > b) {
                a = a % b;
            }
            else {
                b = b % a;
            }
        }
        if (a == 0) {
            return b;
        }
        return a;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        int a = 98, b = 56;
        System.out.println("GCD of " + a + " and " + b
                           + " is " + gcd(a, b));
    }
}

Python3




# Itervative function to return gcd of a and b
def gcd(a, b):
 
    # Everything divides 0
    while(a > 0 and b > 0):
        if (a > b):
            a = a % b
        else:
            b = b % a
 
    if (a == 0):
        return b
    return a
 
 
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')

Javascript




<script>
 
// Javascript program to find GCD of two number
 
// Recursive function to return gcd of a and b
 
function gcd(a, b){
   
  // Everything divides 0
      while (a > 0 && b > 0) {
        if (a > b) {
            a = a % b;
        }
        else {
            b = b % a;
        }
    }
    if (a == 0) {
        return b;
    }
    return a;
}
 
// Driver code
let a = 98;
let b = 56;
 
document.write(`GCD of ${a} and ${b} is ${gcd(a, b)}`);
 
// This code is contributed by _saurabh_jaiswal
 
</script>

C#




// C# program to find GCD of two
// numbers
using System;
 
class GFG {
 
    // Iterative function to return
    // gcd of a and b
    static int gcd(int a, int b)
    {
        while (a > 0 && b > 0) {
            if (a > b) {
                a = a % b;
            }
            else {
                b = b % a;
            }
        }
        if (a == 0) {
            return b;
        }
        return a;
    }
 
    // Driver method
    public static void Main()
    {
        int a = 98, b = 56;
        Console.WriteLine("GCD of " + a + " and " + b
                          + " is " + gcd(a, b));
    }
}
 
// This code is contributed by anuj_67.

Output

GCD of 98 and 56 is 14

Time Complexity: O(log(min(a,b))|
Auxiliary Space: O(1)

Another Approach: using the inbuilt gcd function (c++14 and above)

syntax:

#include<algorithm>
__gcd(a,b)
a and b are the numbers whose gcd we have to find

C++




// c++ program to find gcd using inbuilt functions
#include <algorithm>
#include <iostream>
using namespace std;
 
int main()
{
 
    int a = 9, b = 27;
    cout << "The gcd of a and b is " << __gcd(a, b) << endl;
    return 0;
}

Output:

The gcd of a and b is 9

Time Complexity: O(logn)
Auxiliary Space: O(1)

Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!