0

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;
}
Shouvik
  • 449
  • 1
  • 7
  • 17
  • What do you want to happen instead? You know that numbers on computers are limited to fixed ranges, right? – j_random_hacker Apr 03 '15 at 09:24
  • @j_random_hacker There are some workarounds for this issue... – lodo Apr 03 '15 at 09:26
  • @j_random_hacker: yes you are right. I am looking for a workaround here. Btw Thanks for the suggestion lodo – Shouvik Apr 03 '15 at 09:27
  • I would not use Javascript for math computation. – Luc DUZAN Apr 03 '15 at 09:38
  • 1
    Actually the max integer in javascript is 2^53 = 9007199254740992. That value is already exceeded by 19! Look here http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin – Tesseract Apr 03 '15 at 09:52

2 Answers2

2

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?

Community
  • 1
  • 1
lodo
  • 2,314
  • 19
  • 31
0

You can:

  1. Use BigInteger

  2. Use floats with the Stirling formula

http://en.wikipedia.org/wiki/Stirling%27s_approximation