# [SOLVED] overflow when calculate factorial

• 05-03-2009, 06:28 AM
ravinda
[SOLVED] overflow when calculate factorial
I code a factoial calculating program with self implemented stack. i use long for stack data type. but for values such as 21! it gives a minus value. why is this happening and how to solve it. :confused:
• 05-03-2009, 07:07 AM
angryboy
21! = 51090942171709440000.
what is the max value for long?

You need to use java.math.BigInteger
• 05-03-2009, 07:12 AM
pbrockway2
Code:

```          21! =  51090942171709440000 Long.MAX_VALUE = 9223372036854775807```
Quote:

why is this happening and how to solve it.
As you yourself say, it's overflowing. Try a more appropriate data type like BigInteger. Or, depending on the accuracy required, an approximation like Stirling's formula.
• 05-04-2009, 04:41 AM
Eranga
A bit more explanation.

I'll just compare this with int and BigInteger. If you are working on with int, after the 12 int produce a garbage. Actually long makes it to 20. Basically throws all the bits out of the range, 32bits for int and 64bits for long. BigInteger also have a limit, which is only on the limit of memory you have.
• 05-04-2009, 06:48 PM
ravinda
Got the Solution
I try using BigInteger and it works. It works fine for last numbers like 1000!. thanks for every one who try to help. Specially to Eranga. Thank you.
• 05-05-2009, 05:07 PM
Eranga
It's pleasure to help you lol. :)

So you've solved the problem, please mark the thread solved. You can fin the option on the 'Thread Tools' on top menu of the first post in this thread.

Good luck!
• 05-05-2009, 05:07 PM
Eranga
It's pleasure to help you lol. :)

So you've solved the problem, please mark the thread solved. You can fin the option on the 'Thread Tools' on top menu of the first post in this thread.

Good luck!