What is wrong with this recursion function? fac(5) gives NaN
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
NaN - not a number error , occurs usually but not limited to when we try to apply a numerical operation to a value which is not a number.
The Issue at hand is when the input value is less than 2 , the function return undefined, which is not a number, so the return (num*fac(num-1)) will fail due to num * undefined.
to fix this , we have to return a value when number is 2 or less than 2.
function fact(num) {
if(num > 2)
return num * fact(num - 1);
else
return num;
}
What's wrong with your code
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
No return value for num <= 2. So, at some point your code will multiply Number with undefined which results in NaN
while loop is not needed
function fac(num) {
return (num > 2) ? num * fac(num - 1) : 1;
}
alert(fac(5));
num <= 2. So at some point your code will multiply thenumberwithundefined