Calculating the Greatest Common Divisor in JavaScript

Last Updated : 24 Aug, 2026

The Greatest Common Divisor (GCD) of two or more numbers is the largest positive integer that divides all the given numbers without leaving a remainder.

For example:

Input:  [2, 4, 6, 8]
Output: 2

The GCD of multiple numbers can be calculated by repeatedly finding the GCD of two numbers:

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

For an array, we can start with the first element and calculate its GCD with each subsequent element.

The following approach can be used to calculate the GCD of two or more numbers in JavaScript.

Approach: Using the Euclidean Algorithm

The Euclidean Algorithm calculates the GCD by repeatedly replacing the larger number with the remainder obtained by dividing the two numbers.

  • Create a gcd() function that accepts two numbers.
  • Use the remainder operator (%) to calculate the remainder.
  • Continue until the second number becomes 0.
  • For an array, use reduce() to calculate the GCD of all elements.
  • If the GCD becomes 1, return 1 immediately because no smaller positive GCD is possible.

Example 1: This example calculates the GCD of all the elements in an array.

JavaScript
function gcd(a, b) {
    a = Math.abs(a);
    b = Math.abs(b);

    while (b !== 0) {
        [a, b] = [b, a % b];
    }

    return a;
}

function findGCD(arr) {
    if (arr.length === 0) {
        return 0;
    }

    return arr.reduce((result, current) => {
        return gcd(result, current);
    });
}

const arr = [2, 4, 6, 8, 16];

console.log(findGCD(arr));

Output
2

Syntax:

gcd(a, b);
  • a and b are the two numbers whose GCD is calculated.
  • The gcd() function returns their greatest common divisor.
  • findGCD() applies the same operation to all elements of the array.

Time Complexity: O(n log M), where n is the number of elements and M is the largest element.

Auxiliary Space: O(1), excluding the space used by the input array.

Comment