Search code examples
javascriptalgorithmeulers-number

Why my method to get euler numbers, return infinity?


Im trying to get the euler number, with Javascript.

Here my code, that return infinity:

function euler_number() {
  for(var j = 0, e = 0; j < 10; j++) {
      e += 1/(factorial(j));
  }
  return e;
}

function factorial(n) {
  if(n <= 1) return n;
  return factorial(n - 1) * n;
}

var r = euler_number();

console.log(r);

so, i cant understand why it return infinity.


Solution

  • This code returns infinity because the initial value of j is 0. In particular, you're adding 1/factorial(0) to e. What does factorial(0) return? JavaScript evaluates 1/0 as Infinity, so after the first iteration, e is already Infinity, and any subsequent iterations add more to it.

    To fix this, just start j at 1. That should do the trick!

    Edit: Vasan had a great point, which is that 0! (0 factorial) actually evaluates to 1. For a better fix, you should reevaluate your factorial function.