I was solving some problems on project euler and I wrote identical functions for problem 10...
The thing that amazes me is that the C solution runs in about 4 seconds while the python solution takes about 283 seconds. I am struggling to explain to myself why the C implementation is so much faster than the python implementation, what is actually happening to make it so?
C:
#include <stdio.h>
#include <time.h>
#include <math.h>
int is_prime(int num)
{
int sqrtDiv = lround(sqrt(num));
while (sqrtDiv > 1) {
if (num % sqrtDiv == 0) {
return(0);
} else {
sqrtDiv--;
}
}
return(1);
}
int main ()
{
clock_t start = clock();
long sum = 0;
for ( int i = 2; i < 2000000; i++ ) {
if (is_prime(i)) {
sum += i;
}
}
printf("Sum of primes below 2,000,000 is: %ld\n", sum);
clock_t end = clock();
double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
printf("Finished in %f seconds.\n", time_elapsed_in_seconds);
}
Python:
from math import sqrt
import time
def is_prime(num):
div = round(sqrt(num))
while div > 1:
if num % div == 0:
return False
div -= 1
return True
start_time = time.clock()
tsum = 0
for i in range(2, 2000000):
if is_prime(i):
tsum += i
print tsum
print('finished in:', time.clock() - start_time, 'seconds')