Duncan's blog

October 15, 2014

Project Euler: problem 48 (PHP) – Self powers

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

48I previously blogged about this Project Euler puzzle nearly 6 years ago, using 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 48:

The series, 11 + 22 + 33 + … + 1010 = 10405071317.

Find the last ten digits of the series, 11 + 22 + 33 + … + 10001000.


$limit = 1000;
$sum = 0;

foreach (range(1, $limit) as $i) {
	$sum = bcadd($sum, bcpow($i, $i));

echo substr($sum, -10);

Short question, short answer.  Using the BC Math functions due to the size of the numbers involved… not quite as fast to spit out the answer as it was with Python though.  Here using PHP’s substr() function which seems more useful than ColdFusion’s Mid() as by specifying a negative number it allows us to start 10 characters from the end of the string… and the third parameter is optional for the length required.


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: