I’m experiencing the strangest problem and have been having a terrible time debugging it. I thought I’d post it here to get any opinions.
public static void sieve(int limit) {
for (int i = 2; i < limit; i ++) {
if (mPrimes[i] == true) {
for (int j = i*i; ((j < limit) && (j > 0)); j += i) {
mPrimes[j] = false;
}
}
}
}
(assume mPrimes are all initially true)
Here’s the catch:
When I run this program with limits of 10, 100, 1000, 10000, and even 100000, it reports counting the correct number of primes below the given number, as cross-referenced with this page: http://primes.utm.edu/howmany.shtml
However, when I run with an argument of 1000000 (one million), I get a result that is exactly 7 away from the correct value (it reports 78491 instead of 78498).
Furthermore, All the other methods of prime-counting I’ve implemented in this program report the correct value.
And here’s the real catch: If I replace
i*i
with
i+i
As to start “crossing out” directly from the seed value, instead of starting from the square (which is what my professor had done in his sample code), it works.
This leaves me only to assume that something strange is happening with the square when i is very large.
Any suggestions?
Its an overflow error. 1,000,000 * 1,000,000 needs more bits than an int (2*32 – 1) can accommodate. You need to use a long (2*64 -1).