Greatest Common Divisor (GCD)

The Greatest Common Divisor (GCD), also known as the Highest Common Factor (HCF), of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers.

The GCD of two non-negative integers a and b, not both zero, is the largest positive integer d such that d divides a and d divides b.

Algorithms for GCD

1. Euclidean Algorithm

The most efficient and common algorithm for computing the GCD is the Euclidean Algorithm. It is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. This process is repeated until one of the numbers becomes zero, at which point the other number is the GCD.

A more efficient version uses the modulo operator:


function gcd(a, b) {
    while (b !== 0) {
        let temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
            

Alternatively, a recursive implementation:


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

Example: GCD of 48 and 18

Using the Euclidean Algorithm:

  1. gcd(48, 18)
  2. 48 % 18 = 12. So, gcd(18, 12)
  3. 18 % 12 = 6. So, gcd(12, 6)
  4. 12 % 6 = 0. So, gcd(6, 0)
  5. The second number is 0, so the GCD is the first number: 6.

Therefore, the GCD of 48 and 18 is 6.

2. Brute Force Method (Less Efficient)

This method involves iterating from the minimum of the two numbers down to 1 and checking if each number divides both inputs. The first number found that divides both is the GCD.


function gcdBruteForce(a, b) {
    let smaller = Math.min(a, b);
    for (let i = smaller; i >= 1; i--) {
        if (a % i === 0 && b % i === 0) {
            return i;
        }
    }
    return 1; // Should not reach here if inputs are valid
}
            

This method is generally not recommended for large numbers due to its inefficiency.

Properties of GCD

Applications of GCD

GCD for Multiple Numbers

The GCD of more than two numbers can be found by iteratively applying the GCD function:

gcd(a, b, c) = gcd(gcd(a, b), c)

And for a list of numbers [n1, n2, n3, ..., nk]:

GCD = gcd(n1, gcd(n2, gcd(n3, ..., gcd(nk-1, nk)...)))


function gcdOfList(numbers) {
    if (numbers.length === 0) {
        return 0; // Or throw an error, depending on desired behavior
    }
    let result = numbers[0];
    for (let i = 1; i < numbers.length; i++) {
        result = gcd(result, numbers[i]); // Using the Euclidean algorithm gcd function
    }
    return result;
}