1

I wrote a factorial function using recursion and a while-loop but it's return value is NaN whenever it is called. Please I want to know why? and how to fix it?

Function

function factorial(n) {
    while(n > 0)
        return factorial(n - 1) * n;
}
fiza khan
  • 1,280
  • 13
  • 24
Josh
  • 11
  • 4

4 Answers4

5

You're missing the return statement for the base case. The function returns undefined when you return without a value, and when you multiply that you get NaN.

Also, you're not looping, so you should use if rather than while.

function factorial(n) {
  if (n > 0) {
    return factorial(n - 1) * n;
  } else {
    return 1;
  }
}

console.log(factorial(10));

You can also write it with looping instead of recursion.

function factorial(n) {
  result = 1;
  for (var i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(10));
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

If you track your recursion, you'll see when n reaches 1, which make n-1 = 0 and the factorial(0) is called, your function does not know what to do next and does not return any number (NaN). That NaN multiplies with all other things returning another NaN.

Add an instruction for your function in to handle n = 0:

function factorial(n) { 
   if (n == 0) return 1;
   while(n > 0)
      return factorial(n - 1) * n;
  }
Hung Thai
  • 229
  • 2
  • 7
0

Just add the base case n === 0 to n === 1 to end the tail recursion.

console.log(function factorial(n) {

  if (n === 0 || n === 1) {
    return 1;
  }


  return factorial(n - 1) * n;

}(4));
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
0

you can also write it in single line:

const factorial = (n) => (n > 1) ? factorial(n-1) * n : 1
Cœur
  • 37,241
  • 25
  • 195
  • 267
punksta
  • 2,738
  • 3
  • 23
  • 41