I have the following code but it is not giving perfect result for factorial can u find it out plz
I wrote this and it works.
var d = 1;
for (num; num > 1; num--) {
d *= num;
}
return d;
Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;
var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
.reduce((p,c) => p*c)
: 1;
console.log(fact(5));
function factorial(num) {
var result = 1;
for (var i = 1; i <= num; i++) {
result = result * i;
}
return result;
}
//call function e.g factorial(4).. 1*2*3*4 it will evaluate in ascending order
Use loop its easy to implement
function fact(num)
{
if(num<0)
return "Undefined";
var fact=1;
for(var i=num;i>1;i--)
fact*=i;
return fact;
}
<input type="button" value="Find factiorial" onclick="alert(fact(6))">
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) );
You can try to use recursion method
1) When X=0 function should return 1; 2) Added return;
function fact(num)
{
var x=parseInt(num);
//alert(x+1);
if(x>0)
x=x* fact(x-1);
else
x=1;
return x;
}
usage
<input type="button" value="Find factiorial" onclick="alert(run(fact.value));">