Optimization using division

Instead of the Euclidean algorithm by subtraction, a better approach can be used. 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 the modulo operator in Euclidean algorithm.

Below is the implementation of the above approach.

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.


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>


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
?>


Output

GCD of 98 and 56 is 14

Complexity Analysis:

Time Complexity: 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)).

Auxiliary Space: O(log(min(a,b))

Program to Find GCD or HCF of Two Numbers

Given two numbers a and b, the task is to find the GCD of the two numbers.

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

Examples:

Input: a = 20, b = 28
Output: 4
Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20. The factors of 28 are 1, 2, 4, 7, 14 and 28. Among these factors, 1, 2 and 4 are the common factors of both 20 and 28. The greatest among the common factors is 4.

Input: a = 60, b = 36
Output: 12

Similar Reads

Naive Approach for GCD of two numbers:

The basic idea is to find the minimum of the two numbers and find its highest factor which is also a factor of the other number....

Euclidean algorithm for GCD of two numbers:

...

Optimization by checking divisibility:

...

Optimization using division:

...

Iterative implementation for GCD of two numbers using Euclidean Algorithm:

...

Contact Us