I started working on Project Euler problems today to keep myself busy over break. One of the problems asks for the sum of all prime numbers below 2 million, so I threw together a Sieve of Eratosthenes to find all those numbers.
unsigned long i, j, sum = 0, limit = 2000000;
// Allocate an array to store the state of numbers (1 is prime, 0 is not).
int* primes = malloc(limit * sizeof(int));
// Initialize every number as prime.
for (i = 0; i < limit; i++)
primes[i] = 1;
// Use the sieve to check off values that are not prime.
for (i = 2; i*i < limit; i++)
if (primes[i] != 0)
for (j = 2; i*j < limit; j++)
primes[i*j] = 0;
// Get the sum of all numbers still marked prime.
for (i = 2; i < limit; i++)
if (primes[i] != 0)
sum += i;
printf("%d", sum);
This works perfectly up to limit
around half a million. After this, it returns random values (for example, 1000000 returns -1104303641). I've tried declaring all the unsigned long
variables as unsigned long long
to no avail. The error seems to be happening in the last 4 lines, because primes[]
contains nothing but 1's and 0's at that point. I figure this has something to do with the size of the values being worked with, can anyone offer any guidance?