This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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'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.
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.
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 !!
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.