I have the following code but it is not giving perfect result for factorial can u find it out plz
Here is one I made using a while loop:
function factorialize(num)
{
i = 1;
b = 1;
while (i < num) {
b = b + (b * i);
i = i + 1;
}
return b;
}
I am not sure why no one used dynamic programming to answer this, it's by far the most efficient way to build something on a factorial in my view.
var mem = [];
function fact(num)
{
var x = parseInt(num);
if (x == 0 || x == 1) return 1;
mem[x] = x * fact(x-1);
return mem[x];
}
My suggestion:
function fact(x) {
if (x<0) {
return Infinity
};
var _= 1
for ($=1;$<=x;++$) {
_*=$
};
return _
};
It simply returns the factorial of whatever "x" is.
A slight edit to Anton's code:
function fact(x) {
if(x>0)
return x* fact(x-1);
if(x===0)
return 1;
return null;
}
(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)
a very simple form:
function fact() {
var x = document.getElementById("txtf").value;
var f=1;
for (var i=1; i <= x ; i++){
f = f*i;
}
document.getElementById('showR').innerHTML= f;
}
<input type="text" id="txtf" value="3">
<input type="button" id="btnf" value="click for calculate" onclick="fact()">
<p id="showR">/Factoriel/</p>
alert
, you don't really do anything with the returned value.Try this instead, if you will (hover over the text):
if(x==0) return 1;
return x * fact(x-1);
Working example: http://jsbin.com/apuka3/2