This program runs in about 1.65 seconds on a 1.65GHz dual core processor.
I compile it with:
gcc -Wall -o ./program ./program.c -lm
Are there any optimizations I can use to speed this up, or is it already going about as fast as possible on this machine?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#define LIMIT 2e6
int is_prime(int num, int* primes, int index)
{
double stop = sqrt(num);
int x;
int i;
for(i = 0; i <= index ; ++i) {
if( !(num%primes[i]) ) {
return 0;
}
if( primes[i] > stop ) {
break;
}
}
for(x = primes[index]; x <= stop; x += 2) {
if( !(num%x) ) {
return 0;
}
}
return 1;
}
int main(void)
{
double time_spent;
clock_t begin, end;
begin = clock();
int size = 8;
int* primes;
primes = (int*)malloc(size*sizeof(int));
assert(primes);
int i = 0;
primes[i++] = 2;
unsigned long long int sum = 2;
int candidate = 3;
while( candidate < LIMIT ) {
if( is_prime(candidate, primes, i-1) ) {
if( i >= (size-1) ) {
size *= 2;
primes = (int*)realloc(primes, size*sizeof(int));
assert( primes );
}
primes[i++] = candidate;
sum += candidate;
}
candidate+=2;
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%i primes sum to %llu in %f seconds\n", i-1, sum, time_spent);
return 0;
}