Reputation: 447
I am trying to create a function for calculating factorial of a given number. It works fine until I pass a number greater than 21 to the function. I understand that 21! exceeds the max limit of integer, But then is there a solution for that ! Or I am doing something wrong here ! Please help ! Given below is my function for factorial calculation.
function calculateFactorial(number)
{
var counter = 1;
var factorial = number;
if (number == 1) {
factorial = number;
}
else {
while(counter < number)
{
factorial = factorial * (number - counter);
counter++;
}
}
return factorial;
}
Upvotes: 0
Views: 806
Reputation: 231
You can:
Use BigInteger
Use floats with the Stirling formula
http://en.wikipedia.org/wiki/Stirling%27s_approximation
Upvotes: 0
Reputation: 2383
You should use a BigInteger library for javascript.
You can write it by your own (if you don't need advanced operations, it's quite easy and funny to write), or you can search online. There are tons of those libraries out there:
What JavaScript library can I use to manipulate big integers?
Upvotes: 2