Project Euler Problem 10

Find the sum of all the primes below two million.

PHP Script

<?php
function IsPrime($number) {
	if($number < 2) {
		return;
	}
	$stop = ceil(sqrt($number));
	for($i=2; $i<= $stop; $i++) {
		if($number % $i == 0) {
			return false;
		}
	}
	return true;
}
$sum = 2;
for($i = 3; $i < 2000000; $i+=2) {
	if(IsPrime($i)) {
		$sum += $i;
	}
}
echo $sum;
?>

C Script

#include <stdio.h>
#include <math.h>

int is_prime(int num) {
	int root = sqrt(num) + 1;
	int i = 2;
	while(i < root) {
		if(num % i == 0) {
			return 0;
		}
		i++;
	}
	return 1;
}

int main (int argc, const char * argv[]) {
    int i, sum;
	for(i = 2; i < 2000000; i++) {
		if(is_prime(i)) {
			sum+= i;
			printf("%d - %dn", i, sum);
		}
	}
}

This is perhaps the most efficient method I can come up with.

Leave a Reply

Your email address will not be published.