Thread: [SOLVED] overflow when calculate factorial

1. Member
Join Date
Apr 2009
Posts
4
Rep Power
0

[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:

2. 21! = 51090942171709440000.
what is the max value for long?

You need to use java.math.BigInteger

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
15
Java Code:
```          21! =  51090942171709440000
Long.MAX_VALUE = 9223372036854775807```
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.

4. 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.

5. Member
Join Date
Apr 2009
Posts
4
Rep Power
0

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.

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!

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!

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•