posted 5 years ago

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

Here is my code

"Known is a drop , unknown is an ocean " !

Matthew Brown

Bartender

Posts: 4568

9

posted 5 years ago

Here's the problem: what is the largest number that you can store in a

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

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

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

posted 5 years ago

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

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.

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

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

posted 5 years ago

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 !!

"Known is a drop , unknown is an ocean " !