Why is Java not telling me when I can't use Integer?

Posted by Sebi on Stack Overflow See other posts from Stack Overflow or by Sebi
Published on 2010-05-14T12:52:37Z Indexed on 2010/05/14 12:54 UTC
Read the original article Hit count: 386

Filed under:
|
|
|

For a small project (Problem 10 Project Euler) i tried to sum up all prime numbers below 2 millions. So I used a brute force method and iterated from 0 to 2'000'000 and checked if the number is a prime. If it is I added it to the sum:

private int sum = 0;

private void calculate() {
   for (int i = 0; i < 2000000; i++) {
      if (i.isPrime()) {
         sum = sum + i;
      }
   }
   sysout(sum)
}

The result of this calculation is 1179908154, but this is incorrect. So i changed int to BigInteger and now i get the correct sum 142913828922. Obviously the range of int was overflowed. But why can't Java tell my that? (e.g. by an exception)

© Stack Overflow or respective owner

Related posts about java

Related posts about math