Fastest way to compute GCD

The fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorithm is an efficient and widely used method for GCD calculation. It used to compute GCD of two numbers in O(log(min(a,b)).

It uses recursion to repeatedly replace a with b and b with the remainder of a divided by b until b becomes zero, returning a as the GCD. This approach is concise and efficient for GCD calculation.

Below is the code snippet for above algorithm:

C++




int gcd (int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd (b, a % b);
}


Java




public static int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}


Python3




def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


C#




using System;
 
int Gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return Gcd(b, a % b);
}


Javascript




function gcd(a, b) {
    if (b === 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}


GCD (Greatest Common Divisor) Practice Problems for Competitive Programming

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

GCD (Greatest Common Divisor)

Similar Reads

Fastest way to compute GCD

The fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorithm is an efficient and widely used method for GCD calculation. It used to compute GCD of two numbers in O(log(min(a,b))....

Problems identification that involve GCD (Greatest Common Divisor)

...

Easy Level Problems on GCD

...

Medium Level Problems on GCD

...

Hard Level Problems on GCD

...