Search code examples
javascriptrangegreatest-common-divisor

GCD in JS - Maximum call stack exceeded


This is my recursive code I wrote to calculate the GCD:

function gcd(n1, n2) {
    if(n1<n2) {
        return gcd(n1, n2-n1);
    }
    else if(n2<n1) {
        return gcd(n1-n2,n2);
    }
    else{
        return n1;
    }
}
console.log(gcd(process.argv[2], process.argv[3]));

It gives me a Range Error. Any idea why? :(

EDIT:

I removed the stdin and replaced it with random numbers and it worked fine.

I wonder why it didn't work the first time though...


Solution

  • Try this:

    function gcd(n1, n2) {
        if(n1<n2) {
            return gcd(n1, n2-n1);
        }
        else if(n2<n1) {
            return gcd(n1-n2,n2);
        }
        else{
            return n1;
        }
    }
    console.log(gcd(parseInt(process.argv[2]), parseInt(process.argv[3])));
    

    I think that JavaScript's type coercion is causing a gotcha. With the original version, I can make it get a call stack overflow error like this:

    node gcd.js 3 11