Factorials/Combinations Yields NaN When Not Supposed To
I am solving for y Choose p combinations. I am a beginner with Javascript.
I have produced this definition of the factorial function: It was inteded to do x * (x-1) * (x-2) ... * 1.
function factorial(z)
{
var product = z;
if (z == 0)
{
return 1;
}
else
{
for (var m = 1; m < z; m++)
{
product = m * product;
return product;
}
}
}
I then have this function, which uses the factorial function.
function placeBoxes()
{
var ids = 0;
for (var y = 0; y < (numOfRows-1); y++)
{
for (var p = 0; p < (y+1); p++, ids++)
{
x = document.createElement('div');
x.className = "box";
x.id = ids;
x.innerHTML = (factorial(y))/((factorial(y-p))*(factorial(p)));
document.getElementByI开发者_开发技巧d('holdsBoxes').appendChild(x);
}
}
}
It is supposed to choose the combinations. For experimental purposes, numOfRows is realistically between 5 and 30. 0C0 1C0 1C1 2C0 2C1 2C2 and so on... This is equivalent to 1, 1, 1, 1, 2, 1 and so on...
Does anyone know what I have done wrong? I am getting NaN instead of a value for the second, third, fifth, eighth, ninth, and many other values.
Edit: Thank you everyone! The problem is solved. The factorial function was messed up.
Change
for (var m = 1; m < z; m++)
{
product = m * product;
return product;
}
To
for (var m = 1; m < z; m++)
{
product = m * product;
}
return product;
You're never completing the loop
for (var m = 1; m < z; m++)
{
product = m * product;
return product;
}
Your returning product
inside your loop. Are you sure about this? Don't you want to return product
outside your loop?
This is also the cause of your NaN
. What if z
is 1 ? then m < z
is m < 1
and thats always false. So that loop body is never being called. and the return statement is never called.
So the function returns undefined
. And undefined * 1 === NaN
I believe that the factorial function is incorrect. Try changing it to this:
function factorial(z)
{
var product = z;
if (z == 0)
{
return 1;
}
else
{
for (var m = 1; m < z; m++)
{
product = product*(product - m);
}
return product;
}
}
精彩评论