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);
}
}
|