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;
}
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;
}
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));
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;
}
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));