Search code examples
javascriptalgorithmternary-operatorgreatest-common-divisor

Implementation of Euclidean GCF results in "Range Error: Maximum call stack size exceeded."


I am struggling to get my head around ternary operators, so I thought I'd take a recent example I came across and liked, and try to refactor it into a more basic (albeit verbose) notation. However, my implementation throws an error while the ternary version I am trying to reconstruct works just fine.

The ternary version of Euclid's algorithm for computing the GCF of two numbers:

  function gcd(a, b) {
        return !b ? a : gcd(b, a % b);
    }

And my attempt at implementing it

    function gcf2(a, b) {
    if(b !== a){
      gcf2(b, a % b);
    }
    else {
      g = b;
    }
  }

I've read the MDN description of ternary operators, but it's clear I'm not understanding it just yet from the results.


Solution

  • The way to convert your ternary into an if else statement is this:

    function gcd2(a, b) {
      if (!b) {
        return a;
      }
      else {
        return gcd2(b, a % b);
      }
    }
    

    The ternary is basically saying "If b is falsy, return a. Else return gcd(b, a % b)"