How to calculate GCD of two or more numbers/arrays in JavaScript?

The greatest common divisor (GCD) of two or more numbers, also known as the greatest common factor (GCF) or highest common factor (HCF), is the largest positive integer that divides a given number without a remainder. In other words, the GCD is the largest number that is a divisor of both numbers.

For example, the GCD of 24 and 36 is 12.

Understanding the Euclidean Algorithm

The Euclidean algorithm is the most efficient method to calculate GCD. It works by repeatedly applying the formula: gcd(a, b) = gcd(b, a % b) until one number becomes zero.

The algorithm works as follows:

  • Divide the larger number by the smaller number
  • Replace the larger number with the smaller number
  • Replace the smaller number with the remainder
  • Repeat until the remainder is zero
  • The last non-zero remainder is the GCD

GCD of Two Numbers

Here's how to implement the Euclidean algorithm for two numbers:

<!DOCTYPE html>
<html>
<head>
    <title>GCD Calculator</title>
</head>
<body>
    <h2>GCD of Two Numbers</h2>
    <div id="result1"></div>
    
    <script>
        function gcd(a, b) {
            // Euclidean algorithm
            while (b !== 0) {
                let temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        }
        
        // Example: GCD of 24 and 36
        let num1 = 24;
        let num2 = 36;
        let result = gcd(num1, num2);
        
        document.getElementById("result1").innerHTML = 
            `GCD of ${num1} and ${num2} = ${result}`;
    </script>
</body>
</html>
GCD of 24 and 36 = 12

GCD of Multiple Numbers

To find the GCD of more than two numbers, we use the property: gcd(a, b, c) = gcd(gcd(a, b), c).

<!DOCTYPE html>
<html>
<head>
    <title>GCD Multiple Numbers</title>
</head>
<body>
    <h2>GCD of Multiple Numbers</h2>
    <div id="result2"></div>
    
    <script>
        function gcd(a, b) {
            while (b !== 0) {
                let temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        }
        
        function gcdMultiple(numbers) {
            return numbers.reduce((acc, num) => gcd(acc, num));
        }
        
        // Example: GCD of 48, 18, and 24
        let numbers = [48, 18, 24];
        let result = gcdMultiple(numbers);
        
        document.getElementById("result2").innerHTML = 
            `GCD of ${numbers.join(', ')} = ${result}`;
    </script>
</body>
</html>
GCD of 48, 18, 24 = 6

GCD of Array Elements

Here's a more comprehensive solution that handles arrays of any size:

<!DOCTYPE html>
<html>
<head>
    <title>Array GCD Calculator</title>
</head>
<body>
    <h2>GCD of Array Elements</h2>
    <div id="result3"></div>
    
    <script>
        function gcd(a, b) {
            while (b !== 0) {
                let temp = b;
                b = a % b;
                a = temp;
            }
            return Math.abs(a); // Handle negative numbers
        }
        
        function arrayGCD(arr) {
            if (arr.length === 0) return 0;
            if (arr.length === 1) return Math.abs(arr[0]);
            
            let result = Math.abs(arr[0]);
            for (let i = 1; i < arr.length; i++) {
                result = gcd(result, Math.abs(arr[i]));
                if (result === 1) break; // Optimization
            }
            return result;
        }
        
        // Test with different arrays
        let testArrays = [
            [12, 18, 24],
            [100, 75, 50, 25],
            [7, 14, 21, 28]
        ];
        
        let output = "";
        testArrays.forEach((arr, index) => {
            let result = arrayGCD(arr);
            output += `GCD of [${arr.join(', ')}] = ${result}<br>`;
        });
        
        document.getElementById("result3").innerHTML = output;
    </script>
</body>
</html>
GCD of [12, 18, 24] = 6
GCD of [100, 75, 50, 25] = 25
GCD of [7, 14, 21, 28] = 7

Key Points

  • The Euclidean algorithm is the most efficient method for calculating GCD
  • Time complexity: O(log(min(a, b))) for two numbers
  • For multiple numbers, apply GCD iteratively: gcd(a, b, c) = gcd(gcd(a, b), c)
  • Handle negative numbers by taking absolute values
  • Early termination: if GCD becomes 1, no need to continue

Conclusion

The Euclidean algorithm provides an efficient way to calculate GCD for both pairs of numbers and arrays. Use the iterative approach for multiple numbers by applying GCD successively to get the final result.

Updated on: 2026-03-15T23:19:00+05:30

862 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements