peterschussheim
6/13/2017 - 7:19 PM

Math

Math

function gcd(a, b) { ///Takes two integers and returns the GCD using a recursive algorithm.
    return b ? gcd(b, a % b) : Math.abs(a)
}

gcd(15, 26)


function gcdArray(array) { ///Iterative implementation that accepts an array of integers.
    let i, y,
        n = array.length,
        x = Math.abs(array[0]);
    
    for (i = 1; i < n; i++) {
        y = Math.abs(array[i]);
        
        while (x && y) {
            (x > y) ? x %= y : y %= x;
        }
        x += y;
    }
    return x
}

gcdArray([57,0,-45,-18,90,447])
gcdArray([16, 32, 96])

Math

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.