Find the greatest common divisor of n numbers Just had this as a practice test problem and I'm curious how to optimize for performance. Thanks!

The greatest common divisor (GCD), also called the highest common factor (HCF) of N numbers is the largest positive integer that divides all numbers without giving a remainder.

Write an algorithm to determin the GCD of N positive integers.

function generalizedGCD(num, arr)
{
    // find the factors of lowest member of arr and then check if every other number is divisible
    arr.sort( function( a, b ) { return a-b; });
    const lowest = arr[0];
    const factors = [];

    for ( let i = 1; i &lt;= lowest; i++) {
        if ( lowest % i === 0 ) {
            factors.push(i);
        }
    }

    // now check to see if each member of the factors array divides into each member of the original numbers array. If not, remove it from the array.
    for ( let j = 1; j &lt; num; j++) {
        for ( let k = 0;  k &lt; factors.length; k++) {
            if ( arr[j]  % factors[k] != 0 ) {
                factors.splice( k, 1);
            }
        }
    }

    return factors[factors.length-1];
}
As I am not a native in Javascript, I'll try to review your algorithm:


start from the lowest value and its factor is a good idea to improve speed
for your second loop I suggest you to start not from the lowest factor but start from the biggest factor. GCD is trying to find the biggest factor, So if you start from the biggest number, after you find a number that can divide all number in arr you can break your loop, it's more efficient.
I've tested it with generalizedGCD(2,[27,8]) and it returns 4 instead of 1, why? the problem is in your second loop, the size of factors changed after you delete its element and you accidentally "skip" some elements. If we try to simulate this with the example above:


    generalizedGCD(2,[8,27])
    ...
    k=0 factors=[1,2,4,8]  arr[j]=27 {27 is divisible with factors[k]=1}
    k=1 factors=[1,2,4,8]  arr[1]=27 {27 is not divisible with factors[k]=2}
    k=2 factors=[1,4,8]    arr[1]=27 {27 is not divisible with factors[k]=8} // you skipped 4
    ...
    factors=[1,4]



The solution that I can think is subtract k by 1 so it doesn't "move" when you are deleting an element in factors:


    if ( arr[j]  % factors[k] != 0 ) {
        factors.splice( k, 1);
        k--;
    }




Suggestion for another algorithm

I think it'll be better if you use faster algorithm: Euclid Algorithm. You can find GCD of every number in array by find GCD each two of them.

GCD( GCD( GCD(a[0], a[1]), a[2]), ...)


It's simple recursion:

function gcd(a, b) {
    if(b === 0) {
        return a;
    }

    return gcd(b, a%b);
}

function generalizedGCD(num, arr)
{
    factors = arr[0];

    for ( let i = 1; i &lt; num; i++) {
        factors = gcd(factors, arr[i])
    }

    return factors;
}