Duncan's blog

September 25, 2014

Project Euler: problem 7 (PHP) – 10001st prime

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

Picture by Chris

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 7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

$primes = array(2);
$limit = 10001;
$i = 1;

require 'isPrime.php';

while (true) {
	$i += 2;
	if (isPrime($i)) {
		array_push($primes, $i);
		if (count($primes) == $limit) {

echo $primes[$limit-1];

Here I’ve put my isPrimes function from the third problem into a file of its own, which I’ve then included using require(), not include() – I think this is best practice or maybe I should use require_once().  Then a simple while loop, checking every odd number until I’ve got all the primes I want.  Then output the last element in that primes array.


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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: