Duncan's blog

October 12, 2014

Project Euler: problem 40 (PHP) – Champernowne’s constant

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

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

Problem 40:

An irrational decimal fraction is created by concatenating the positive integers:

0.123456789101112131415161718192021…

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value of the following expression.

d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000

Code:

<?php
$fraction = "";
$total = 1;

foreach (range(1,1000000) as $i) {
    $fraction .= $i;

    if (strlen($fraction) >= 1000000) {
	break;
    }
}

$total *= 
        substr($fraction, 0, 1) * 
        substr($fraction, 9, 1) * 
        substr($fraction, 99, 1) * 
        substr($fraction, 999, 1) * 
        substr($fraction, 9999, 1) * 
        substr($fraction, 99999, 1) * 
        substr($fraction, 999999, 1);

echo $total;

The code is very similar to how I did it in Python and ColdFusion.

Advertisements

1 Comment »

  1. Change foreach loop to while loop

    Comment by duncan — October 14, 2014 @ 9:31 am | Reply


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: