2

What is wrong with this recursion function? fac(5) gives NaN

function fac(num){
 while(num>2){
 return(num*fac(num-1))
 }
}
asked May 4, 2015 at 11:25
2
  • 4
    Coz you haven't handled num <= 2. So at some point your code will multiply the number with undefined Commented May 4, 2015 at 11:26
  • 2
    @VigneswaranMarimuthu add this as an answer so the question could be closed. Commented May 4, 2015 at 11:26

4 Answers 4

4

fac(1) returns nothing, which is undefined, and undefined*1 is NaN, that's why.

Change your code to

function fac(num){
 return num>2 ? num*fac(num-1) : 1;
}
answered May 4, 2015 at 11:26
Sign up to request clarification or add additional context in comments.

Comments

2

The correct way should be:

function fact(num) {
 if(num > 2)
 return num * fact(num - 1);
 else
 return num;
}
answered May 4, 2015 at 11:27

Comments

2

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;
}
answered May 4, 2015 at 11:27

2 Comments

Your first sentence might make people think applying a numerical operation on numbers doesn't produce NaN. Please fix it.
Thanks for pointing it out, have corrected the sentence to depict the same
1

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

answered May 4, 2015 at 11:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.