Duncan's blog

October 1, 2014

Project Euler: problem 16 (PHP)

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

I previously blogged about this Project Euler puzzle nearly 6 years ago. Initially I tried solving it using ColdFusion, but its native functions couldn’t handle the large integers required, although I could have used the Java BigInteger class.  Instead I ended up doing it as my first exercise in Python.  Now I’ve had a go using PHP and I’d appreciate any feedback on my code.

Problem 16:

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

Code:

<?php
$x = 0;
$y = bcpow(2,1000);
$length = strlen($y);

for ($i = 0; $i <= $length; $i++) {
	$x += substr($y, $i, 1);
}

echo $x;

So the only thing worth pointing out was I had to use bcpow() instead of pow() as that ended up just giving me an incorrect value in scientific notation, i .e. like 1.0715086071863E+301.  Whereas bcpow is a function of the BCMath Arbitrary Precision Mathematics library:

“For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.”

And even though this is a separate ‘library’, it’s bundled with core PHP, so nothing additional required for me to load in, which seems to be quite common with PHP I’m discovering.

September 30, 2014

Project Euler: problem 13 (PHP)

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

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
… etc.
53503534226472524250874054075591789781264330331690

Code:

<?php
$numbers = <<<FOO
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
[etc]
FOO;

$sum = 0;

$lines = explode("\r\n", $numbers);

foreach($lines as $line) {
	$sum += $line;
}

echo $sum;

So taking exactly the same approach as with ColdFusion.  And I get the same problem of having the number being output in scientific notation.  But again the first ten digits I need are visible without needing to do anything clever to output the entire number.  Which is a good job, as I’m not sure what I’d need to do!

September 29, 2014

Project Euler: problem 11 (PHP)

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 11

In the 20 x 20 grid below, four numbers along a diagonal line have been marked in red.

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

The product of these numbers is 26 x 63 x 78 x 14 = 1788696.

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20 x 20 grid?

So taking the same approach as before…

<?php
$grid = <<<FOO
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
FOO;

$numbers = array();
$max = 0;

$lines = explode("\r\n", $grid);
 
foreach($lines as $line) {
	$digits = explode(" ", $line);
	
	$numbers[] = array();
	
	foreach($digits as $digit) {
		array_push($numbers[count($numbers)-1], $digit);
	}
}

// across
for ($i = 0; $i < count($numbers); $i++) {
	for ($j = 0; $j < count($numbers[$i]) - 3; $j++) {
		$product = 1;
		for ($k = 0; $k < 4; $k++) {
			$product *= $numbers[$i][$j + $k];
		}
		
		if ($product > $max) {
			$max = $product;
		}
	}
}

// down
for ($i = 0; $i < count($numbers) - 3; $i++) {
	for ($j = 0; $j < count($numbers[$i]); $j++) {
		$product = 1;
		for ($k = 0; $k < 4; $k++) {
			$product *= $numbers[$i + $k][$j];
		}
		
		if ($product > $max) {
			$max = $product;
		}
	}
}

// diagonally 1, \\\\
for ($i = 0; $i < count($numbers) - 3; $i++) {
	for ($j = 0; $j < count($numbers[$i]) - 3; $j++) {
		$product = 1;
		for ($k = 0; $k < 4; $k++) {
			$product *= $numbers[$i + $k][$j + $k];
		}
		
		if ($product > $max) {
			$max = $product;
		}
	}
}

// diagonally 2, ////
for ($i = 3; $i < count($numbers); $i++) {
	for ($j = 0; $j < count($numbers[$i]) - 3; $j++) {
		$product = 1;
		for ($k = 0; $k < 4; $k++) {
			$product *= $numbers[$i - $k][$j + $k];
		}
		
		if ($product > $max) {
			$max = $product;
		}
	}
}

echo $max;

So using the Heredoc syntax to save a multiline string with all the digits.

I use the explode() function twice, initially to turn this string delimited on its line breaks into an array of the individual lines.  Then again to turn each line delimited on its spaces into an array of just the digits.   This being similar to CFML’s ListToArray(), but with some key differences.

The rest of the code is then almost identical to my ColdFusion version.  The only other thing worth mentioning is using foreach(array as item) to loop over the arrays initially, similar to for(item in array) in CFScript.

September 28, 2014

Project Euler: problem 10 (PHP)

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.

September 27, 2014

Project Euler: problem 9 (PHP)

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

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Code:

<?php
for ($a = 1; $a <= 500; $a++) {
	for ($b = 1; $b <= 500; $b++) {
		$pythagoras = ($a * $a) + ($b * $b);
		$c = sqrt($pythagoras);
		
		if ($c == intval($c)) {
			$sum = $a + $b + $c;
			
			if ($sum == 1000) {
				$product = $a * $b * $c;
				
				echo $a . " + " . $b . " + " . $c . " = " . $sum . "<br>";
				echo $a . " * " . $b . " * " . $c . " = " . $product . "<br>";
				break 2;
			}
		}
	}
}

Very similar code to my ColdFusion version.  Previously I used round() to do a comparison and see if my value was an integer.  I thought it would be more appropriate and simpler to just use PHP’s is_int() function, except it didn’t seem to work, I think due to the larger numbers being used.  So I used intval() instead to do a similar comparison as before.

Also I’m specifying break 2 to break out of the parent loop, otherwise break on its own just breaks out of the inner-most loop and we keep running and end up getting the same factors again in a different combination.  What would be nice would be some way to specify break out of the parent loop, without having to know exactly how many loops that is.  My code here is simple enough it’s easy to see there’s only 2 loops, therefore break 2.  However if you’re writing anything complicated with many nested loops it’s not always so obvious.

September 26, 2014

Project Euler: problem 8 (PHP)

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


The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

This question has been slightly changed since I originally did this. Previously it was the product of 5 adjacent digits; now it’s the product of 13 adjacent digits.

<?php
$digits = <<<FOO
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
FOO;

$max = 0;
$limit = 13;

// turn this into a single-line string
$digits = str_replace(["\n", "\r"], "", $digits);

for ($i = 0; $i < strlen($digits); $i++) {
	$sum = 1;
	
	// multiply together our 13 digits
	for ($j = 0; $j < $limit; $j++) {
		$sum *= substr($digits, $i + $j, 1);
	}
	
	if ($sum > $max) {
		$max = $sum;
	}
}

echo $max;

So I’m using the Heredoc syntax, equivalent to cfsavecontent, for a multi-line string. I’m not sure if it would be advantageous in this case to use Nowdoc, or even just appending each line to a single string, but for now Heredoc seems simple and does what I’m looking for.

I expect there’s some de facto convention for what to use for the end identifier (the bit after the <<< and again at the end of the string), but for now FOO will suffice.   Is it covered in any of the PSR coding standards?

So I get rid of the newline and carriage return characters from the string, turning it into one single line string.  Initially I tried doing str_replace(['\n', '\r'], “”, $digits) except that didn’t work because it didn’t like the single quoted characters.  Instead I had to double-quote them, obviously!

Again we find inconsistencies in PHP, this time with the naming of the functions, str_replace() but strlen(), being the equivalent of ColdFusion’s replace() and len().

And substr(string, start[, count]) being more fully-featured than CFML’s mid(string, start, count).  If you use negative numbers it can extract starting from the end of the string.  And if you don’t specify the count parameter, it goes up to the end of the string.

September 25, 2014

Project Euler: problem 7 (PHP)

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

<?php
$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) {
			break;
		}
	}
}

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.

 

September 24, 2014

Project Euler: problem 6 (PHP)

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

The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 – 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Code:

<?php
$sum1 = 0;
$sum2 = 0;

for ($i = 1; $i <= 100; $i++) {
	$sum1 += ($i * $i);
	$sum2 += $i;
}

$sum2 *= $sum2;

$difference = $sum2 - $sum1;

echo "sum1: " . $sum1 . "<br>";
echo "sum2: " . $sum2 . "<br>";
echo "difference: " . $difference . "<br>";

I wanted to do $i squared using an exponentiation operator.  In ColdFusion you do x ^ 2, but that does a bitwise XOR in PHP.  Instead you use x ** 2.  However this was only introduced in PHP 5.6, which wasn’t released until  about 3 weeks ago! I’m currently running 5.5 so didn’t have access to that.  By contrast ColdFusion has had an exponentiation operator since at least 4.5 (released 1999), and I suspect it’s been in there since version 1 or 2.

So instead you can simply do $i * $i as I’ve done here, or I could also have used the pow() function.  If I was doing anything more complex than squaring it, that’s what I’d have done obviously.

September 23, 2014

Project Euler: problem 5 (PHP)

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

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

Code:

<?php
$step = 20;
$factor = $step - 1;
$i = $step;

while (true) {
	if ($i % $factor == 0) {
		if ($factor == 11) {
			break;
		}
		
		$factor--;
		
		$step = $i;
	} else {
		$i += $step;
	}
}

echo $i;


So a simple while loop that I break out of once we get down to 11.

September 22, 2014

Project Euler: problem 4 (PHP)

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

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Nice and easy:

<?php
$palindrome = 0;

for ($i = 100; $i <= 999; $i++) {
	for ($j = 100; $j <= 999; $j++) {
		$x = $i * $j;
		if ($x > $palindrome && $x == strrev($x)) {
			$palindrome = $x;
		}
	}
}

echo $palindrome;


strrev() being the PHP equivalent of ColdFusion’s more obviously-named reverse().

Next Page »

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 537 other followers