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:

Printable View

- 05-03-2009, 07:28 AMravinda[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, 08:07 AMangryboy
21! = 51090942171709440000.

what is the max value for long?

You need to use java.math.BigInteger - 05-03-2009, 08:12 AMpbrockway2Code:
`21! = 51090942171709440000`

Long.MAX_VALUE = 9223372036854775807

Quote:

why is this happening and how to solve it.

- 05-04-2009, 05:41 AMEranga
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, 07:48 PMravindaGot 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, 06:07 PMEranga
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, 06:07 PMEranga
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!