You are on page 1of 5

sign up log in tour help Search Q&A

Questions Jobs Documentation Beta Tags Users Badges Ask Question

x Dismiss

Join the Stack Overflow Community

Stack Overflow is a community of 4.7 million


programmers, just like you, helping each other.
Join them; it only takes a minute:

Sign up

When calculating the factorial of 100 (100!) with Java using integers I get 0

asked 5 years ago


When doing this:
viewed 15432 times
10 int x = 100;
int result = 1; active 10 months ago
for (int i = 1; i < (x + 1); i++) {
result = (result * i);
}
System.out.println(result); BLOG
4
International salaries at Stack Overflow
This is clearly because the result is too big for an integer, but I am used to get big negative
numbers for the overflow, and not 0.

Thanks in advance! Linked


95
When I switch to this: Why does i = i + i give me 0?

int x = 100; 119


int result = 1; How does Java handle integer underflows and
overflows and how would you check for it?
for (int i = 1; i < (x + 1); i++) {
result = (result * i); 45
System.out.println(result); How to handle very large numbers in Java without
} using java.math.BigInteger

I get this. 4
Find factorial of large numbers in Java
java overflow int factorial
1
share improve this question edited Jun 13 '14 at 15:11 asked Mar 15 '11 at 20:36 Handling 100! in Java / Groovy

0
MC Emperor Trufa Can I can use Java to doSeeking 1 + 2 ! + 3 ! +
4,025 7 36 75 14.6k 26 91 154 + 20 ! And?

Related
2 This is not the best way to calculate a factorial. You know that, right? duffymo Mar 15 '11 at 20:41

1 You're loop wouldn't calculate factorial even if you wouldn't get 0. RoflcoptrException Mar 15 '11 at 20:41
4
@duffymo: Yes, I'm just curious about the output. Thanks! Trufa Mar 15 '11 at 20:41
Dynamic Java integer/long overflow checking
@Roflcoptr: I think it does, I just tested it for 9 with the correct result. Trufa Mar 15 '11 at 20:44
versus performance
@duffymo Of course! After all, if I want 5! , I'm not gonna do 5*4*3*2*1 . I'm gonna evaluate
gamma(6) ! Cole Johnson Jun 16 '14 at 0:09
2
How to get rid of integer overflow warning?

7 Answers active oldest votes 3


Factorial in Java

Big negative numbers are values that overflowed into certain ranges; factorial(100) has more 2
than 32 binary zeros on the end, so converting it to an integer produces zero.
17 Calculating factorial on FORTRAN with integer
share improve this answer answered Mar 15 '11 at 20:41 variables. Memory overflow

0
Jeremiah Willcock
18.8k 2 48 69
(Java) How to use extended precision arithmetic to
handle bigger factorials?
+1, this seems to be correct, thank you very much. Very interesting!! Trufa Mar 15 '11 at 20:49
0
Calculate Large Factorials Using Nodes in Java

Did you find this question interesting? Try our newsletter 1


Java: avoiding factorial overflow
Sign up for our newsletter and get our top new questions
delivered to your inbox (see an example). email address Subscribe
2
Java: How to solve a large factorial using arrays?
There are 50 even numbers between 1 and 100 inclusive. This means that the factorial is a multiple
of 2 at least 50 times, in other words as a binary number the last 50 bits will be 0. (Actually it is -2
16 more as even second even number is a multiple of 2*2 etc)
Efficiently calculate factorial in 32-bit machine

public static void main(String... args) {


BigInteger fact = fact(100); 0
System.out.println("fact(100) = " + fact);
System.out.println("fact(100).longValue() = " + fact.longValue()); Finding average of two numbers using only ints
System.out.println("fact(100).intValue() = " + fact.intValue());
int powerOfTwoCount = 0; Hot Network Questions
BigInteger two = BigInteger.valueOf(2);
while (fact.compareTo(BigInteger.ZERO) > 0 && fact.mod(two).equals(BigInteger.ZERO)) { Writing referee report: found major error, now
powerOfTwoCount++; what?
fact = fact.divide(two); Zero Emission Tanks
}
System.out.println("fact(100) powers of two = " + powerOfTwoCount); Release/Debug has different result for std::min,
} why?

private static BigInteger fact(long n) { Folding Numbers


BigInteger result = BigInteger.ONE; I have hundreds of friends. What am I?
for (long i = 2; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i)); Why do most log files use plain text rather than a
return result; binary format?
}
Movie about a guy who uses a notebook to relive
and fix horrible accidents that he and his friends
caused
prints
Find the Swirling Words!

fact(100) = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185
The commuter's journey
fact(100).longValue() = 0
fact(100).intValue() = 0 My math students consider me a harsh grader. Is
fact(100) powers of two = 97 my teaching attitude wrong?

What elementals can I summon with Summon


Monster?
This means a 97-bit integer would be 0 for the lowest bits of fact(100)
Why did the One Ring betray Isildur?
In fact, the number of powers of two is very close to n for fact(n). For fact(10000) there are 9995 Is the NHS wrong about passwords?
powers of two. This is because its is approximately the sum of n times powers of 1/2 giving a total
close to n . i.e. every second number is even n/2 and every 4th has an additional power of 2 (+n/4) What is the proper position for quick-release
levers?
and every 8th has an additional power (+n/8) etc approaches n as a sum.
Saffron and coloration - is there a way to know
share improve this answer why it gave the wrong color?
edited Mar 15 '11 at 21:40 answered Mar 15 '11 at 20:51
What does 'apt-get install update' do?

Why weren't the invading forces stopped before


Peter Lawrey
reaching US soil in Red Dawn?
349k 40 391 710
Numerical coincidence? Why is sum(x^(k^2)) =
sum(x^((k+1/2)^2)) for x = 0.8?
1 @Trufa: try this program with printing the ( BigInteger and int ) results after every step, to gain more
insight. Palo Ebermann Mar 15 '11 at 21:02 Negotiating the use of a software with my
company
@PaloEbermann: I did, I actually was able to solve this problem, but was curious about the 0 result. Thanks! Term for "professional" who doesn't make their
Trufa Mar 15 '11 at 21:11 living from that kind of work

1 @Peter This is very interesting! Thank you very much! Trufa Mar 15 '11 at 21:11 How to make the development and use of Steam
Engines preferred over that of Combustion
Hopefully I have explained why you get so many 0 bits at the end of the answer which is all you are left with Engines?
when you do a large factorial. in fact fib(34).intValue() == 0 Peter Lawrey Mar 15 '11 at 21:12
The "functions" of untyped lambda calculus are
not (set theoretic) functions so what are they?
1 Misleading method name :) RonK Mar 15 '11 at 21:40
"Everyone has their own stories" vs "Everyone has
show 2 more comments their own story" - which one is correct?

Arithmetic overflow error

To have a look at the cause, we could observe the prime factorization of the factorial.

8 fac( 1) = 1 = 2^0
fac( 2) = 2 = 2^1
fac( 3) = 2 * 3 = 2^1 * 3
fac( 4) = 2 * 2 * 2 * 3 = 2^3 * 3
fac( 5) = ... = 2^3 * 3 * 5
fac( 6) = ... = 2^4 * 3^2 * 5
fac( 7) = ... = 2^4 * ...
fac( 8) = ... = 2^7 * ...
fac( 9) = ... = 2^7 * ...
fac(10) = ... = 2^8 * ...
fac(11) = ... = 2^8 * ...
...
fac(29) = ... = 2^25 * ...
fac(30) = ... = 2^26 * ...
fac(31) = ... = 2^26 * ...
fac(32) = ... = 2^31 * ...
fac(33) = ... = 2^31 * ...
fac(34) = ... = 2^32 * ... <===
fac(34) = ... = 2^32 * ... <===
fac(35) = ... = 2^32 * ...
fac(36) = ... = 2^34 * ...
...
fac(95) = ... = 2^88 * ...
fac(96) = ... = 2^93 * ...
fac(97) = ... = 2^93 * ...
fac(98) = ... = 2^94 * ...
fac(99) = ... = 2^94 * ...
fac(100)= ... = 2^96 * ...

The exponent for the 2 is the number of trailing zeros in the base-2 view, as all other factors are
odd, and thus contribute a 1 in the last binary digit to the product.

A similar scheme works for other prime numbers, too, so we can easily calculate the factorization of
fac(100) :

fac(100) = 2^96 * 3^48 * 5^24 * 7^16 * 11^9 * 13^7 * 17^5 * 19^5 * 23^4 *
29^3 * 31^2 * 37^2 * 41^2 * 43^2 * 47^2 *
53 * 59 * 61 * 67 * 71 * 73 * 79 * 83 * 89 * 97

So, if our computer stored the numbers in base 3, and had 48-trit-numbers, fac(100) would be 0
(as fac(99) , too, but fac(98) would not :-)

share improve this answer answered Mar 15 '11 at 21:35

Palo Ebermann
48k 10 86 148

Nice problem - answer is: Factorial of 33 (due to negative values) is -2147483648 which is
0x80000000 , or 0xFFFFFFFF80000000 if taking 64bits. Multiplying by 34 (the next member) will
6 give a long value of 0xFFFFFFE600000000 , which when casting to int will give you 0x00000000 .

Obviously from that point onwards you will remain with 0.

share improve this answer answered Mar 15 '11 at 20:47

RonK
5,518 5 30 69

Simple solution using recursion and BigIntegers:

public static BigInteger factorial(int num){


if (num<=1)
return BigInteger.ONE;
else
return factorial(num-1).multiply(BigInteger.valueOf(num));
}

Output:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000

share improve this answer answered Nov 22 '15 at 2:20

Jack Ca
33 8

(Found here, adapted slightly to fit question)

0 public static void main(String[] args) {

BigInteger fact = BigInteger.valueOf(1);


for (int i = 1; i <= 100; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}

share improve this answer answered Jul 26 '15 at 9:02

BbJug
25 6
it's an overflow for sure, you can try double, 64 bit long integer are probably too small

-1 share improve this answer answered Mar 15 '11 at 20:45

Julien Vermillard
2,216 1 8 12

Yes, there are -- a quick count shows more than 75 zeros, which is more than the 64 bits in a long.
Jeremiah Willcock Mar 15 '11 at 20:47

Hi, thanks! this should be an comment, not an answer, and no, for 100 it would still be too small, the only way
is using BigInteger Trufa Mar 15 '11 at 20:47

@Trufa: If you only need the result approximately, you could use double for this - it would be much faster
than BigInteger. Palo Ebermann Mar 15 '11 at 21:04

Your Answer

Sign up or log in Post as a guest

Sign up using Google Name

Sign up using Facebook


Email

required, but never shown


Sign up using Email and Password

Post Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged java overflow int factorial or ask
your own question.

question feed

about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback

TECHNOLOGY LIFE / ARTS CULTURE / RECREATION SCIENCE OTHER

Stack Overflow Programmers Database Code Review Photography Academia English Bicycles Mathematics Philosophy Stack Apps
Administrators Language &
Server Fault Unix & Linux Magento Science Fiction more (8) Usage Role- Cross Validated more (3) Meta Stack
Drupal Answers & Fantasy playing (stats) Exchange
Super User Ask Different Signal Skeptics Games
(Apple) SharePoint Processing Graphic Design Theoretical Area 51
Web Mi Yodeya Anime & Computer
Applications WordPress User Experience Raspberry Pi Movies & TV (Judaism) Manga Science Stack
Development Overflow
Ask Ubuntu Mathematica Programming Music: Practice Travel more (18) Physics Careers
Geographic Puzzles & Code & Theory
Webmasters Information Salesforce Golf Christianity MathOverflow
Systems Seasoned
Game ExpressionEngine more (7) Advice English Chemistry
Development Electrical Answers (cooking) Language
Engineering Learners Biology
TeX - LaTeX Cryptography Home
Android Improvement Japanese Computer
Enthusiasts Personal Language Science
Finance &
Information Money Arqade
Security (gaming)

site design / logo 2016 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required
rev 2016.10.7.4047

You might also like