This week's book giveaway is in the OCAJP forum.We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# Incorrect Output !

vamsi acharya
Ranch Hand
Posts: 55
hello guys , I've written a code for calculating factorial of a number ......The code compiles fine and even gives precise output till 20 and after the number 20 even numbers get a negative integer as output and odd numbers get positive integers...please help me out with this .

Here is my code

Matthew Brown
Bartender
Posts: 4568
9
Here's the problem: what is the largest number that you can store in a long variable? Now, how big is 21! ?

What you're seeing is called overflow - the number gets too big for the variable storing it, and wraps around. What you actually see (including the negative numbers) is down to the way that numbers are stored internally in a long variable in binary form.

If you need to calculate factorials bigger than this, take a look at the BigInteger class.

fred rosenberger
lowercase baba
Bartender
Posts: 12183
34
What is the maximum value that a Long can store?

Dang...missed it by 24 seconds...

Rob Spoor
Sheriff
Posts: 20606
60
long can only go up to 2^63 - 1 which is 9,223,372,036,854,775,807 (available as Long.MAX_VALUE). 20! is 2,432,902,008,176,640,000 which is smaller than Long.MAX_VALUE. 21! however is 51,090,942,171,709,400,000 which is over 5 times as large as Long.MAX_VALUE. As a result, the value overflows, and the number can become negative*. This is exactly what's happening here.

If you need to work with numbers larger than Long.MAX_VALUE you have four options:
1) Use a float. You lose a lot of precision though.
2) Use a double. You lose precision but less than with float.
3) Use BigInteger. This is the preferred option.
4) Use BigDecimal. It can do what BigInteger can but adds unnecessary support for non-integer parts.

Matthew Brown
Bartender
Posts: 4568
9
Three within a minute

vamsi acharya
Ranch Hand
Posts: 55
Thank you very much guys , i got my answer ,i owe you guys a lot ,Got to be wary of overflow now , roger that ,I din't really know 21! could actually go beyond the long range , i used int initially this problem has occurred and then i used a wider range long still the problem prevailed so i was kind of confused !!

Campbell Ritchie
Sheriff
Posts: 49733
69
• 1
Overflow is a standard problem; if you try to work out how many milliseconds there are in a month you get 31 * 24 * 60 * 60 * 1000 and you have to look in Bloch and Gafter's Java™ Puzzlers to find the correct solution.