I have the following code but it is not giving perfect result for factorial can u find it out plz
What about:
function fact(n) {
n = Math.round(n);
if (n < 2) {
return 1;
}
else {
return n * fact(n - 1);
}
}
?
You need to have a return
in your function in the first place. ;)
function factorial (n) {
if (n > 1) {
return n * factorial(n-1);
}
return 1;
}
console.log("recursive way => ",factorial(5));
i am quite new to javascript and would be happy to know any improvements that could be made to this answer
var a = 1;
function factorial(num) {
if (num == 0) {
return 1;
} else if (num < 0) {
return undefined;
} else {
for(i = num; i > 0; i--){
a *= i;
}
return a;
}
}
var b = factorial(5);
console.log(b);