GCD via Euclid's Theorem

Euclid's theorem | Worked out example


    function GCD(x, y)
    {
        var max = Math.max(x, y);
        var min = Math.min(x, y);

        if(max%min === 0){
            return min;
        } else {
            return GCD(parseInt(max%min), min);
        }
    }

    console.log(GCD(1071, 462));
    21

Which we can convert to:


    function GCD(x, y)
    {
        var max = Math.max(x, y);
        var min = Math.min(x, y);

        return max%min === 0 ? min : GCD(parseInt(max%min), min);
    }

Of course, you need to check for number being positive only etc.

Same code in CoffeeScript:


    gcd = (x,y) ->
      min = Math.min(x, y)
      max = Math.max(x, y)
      return min if max%min == 0
      return gcd(max%min, min)

    console.log(gcd(1071, 462))