The Euclidean Algorithm

The Euclidean Algorithm

·

2 min read

Let's first see a leetcode problem Find Greatest Common Divisor of Array. This problem is pretty easy. What we may do is to just calculate the max and min values, and loop from min to 1 to find the first divisor. So the solution code may looks like below.

function findGCD(nums: number[]): number {
    let min = 1001;
    let max = 0;
    for (const num of nums) {
        if (num > max) {
            max = num;
        }
        if (num < min) {
            min = num;
        }
    }

    for (let num = min; num > 1; num--) {
        if (max % num === 0 && min % num === 0) {
            return num;
        }
    }

    return 1;
};

As you can see, we need to loop from min to 1. So if the min value is very big, then this may takes time.

The Euclidean algorithm, is an efficient method for calculating the greatest common divisor (GCD) of two integers (numbers). So the problem is basically the same as this leetcode problem.

The idea of this algorithm is based on this:

a = bq + r
gcd(a, b) = gcd(b, r)

As you can see, a is the bigger value, and we can calcuate the remainder r. Then the gcd(a, b) is equal to gcd(b, r). So with this approach, we can convert problem to calculate bigger numbers into problem to calculate smaller numbers. Until we get the remainder as 0, then we get the final result.

For now I don't know how to prove this equation, it may takes some math. Let's just see how to use it to solve this problem in this article.

Here is the code.

function findGCD(nums: number[]): number {
    let min = 1001;
    let max = 0;
    for (const num of nums) {
        if (num > max) {
            max = num;
        }
        if (num < min) {
            min = num;
        }
    }

    while (min !== 0) {
        // min <- remainder
        // max <- min
        [max, min] = [min, max % min];
    }

    return 1;
};