Project Euler Problem 17

December 27, 2011

I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 17 here.

The Problem
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.

The Solution
The reason I love this solution is I found a PHP library that writes out these numbers for you. It comes from PECL 1.0 and is part of PHP 5.3 via that NumberFormatter class. This class did most of the work for me.

<?
$res = "";

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);

for($i = 1; $i format($i));
	if($i > 100 && $i % 100 != 0) {
		$res .= 'and';
	}
}
echo strlen($res)."\n";

My first submission was incorrect and I quickly figured out it was because the NumberFormatter class was missing the “and” after the hundreds. I simply added that at the end since we’re only looking for a count and came up with the correct result.

Installing the NumberFormatter class in Debian squeeze was pretty easy. I simply had to install the PHP5 international compatibility package: sudo apt-get instal php5-intl

Author

Stay in Touch!

Stay in Touch!
Solutions Architecture

browse through our blog articles

Blog Archive