Duncan's blog

September 28, 2014

Project Euler: problem 10 (PHP) – Summation of primes

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 10:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

So initially I tried to do a straight conversion of the CFML code I’d blogged last time, but couldn’t get it to work.  When I’d done this originally I’d simply looped up to two million, adding up all the primes.  Then I rewrote it to be more efficient.  So this time I ended up doing the opposite; I simplified the code to simply add up all the primes.  It wasn’t fast, but it worked.

<?php
ini_set('max_execution_time', 100);

include 'isPrime.php';

$limit = 2000000;
$sum = 2;	// not counting 1 as a prime

for ($i = 3; $i < $limit; $i += 2) {
	if (isPrime($i)) {
		$sum += $i;
	}
}

echo $sum;

Initially this script kept timing out with a “Maximum execution time of 30 seconds exceeded” error message.  So I added the init_set() call to make it a bit longer.  I’m not sure if this is the done thing, or if it’s better to set it directly in php.ini, or something else.

I’m re-using my isPrime function from the third problem, included in its own file, then simply loop over every odd number greater than 1.

In my final ColdFusion version, I had an array which I pre-populated with two million values.  Doing this in PHP using $numbers = array_fill(1, $limit, 1); would consistently fail due to ‘Allowed memory size of xxx bytes exhausted‘.  I tried ramping up the bytes using ini_set(‘memory_limit’, ‘xxxM’); but that made no difference. Which is why I ended up just going with the simpler version of the code.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: