(No Ratings Yet)

## Project Euler 17

#### Problem Description

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.

#### Analysis

Converted the integers from 1 to 999 to the written equivalent, removed spaces and hyphens, added the character count for each one, including “onethousand”.

#### Solution

Runs < 1 second in Perl.

```@D{0 .. 20, 30,40,50,60,70,80,90} = qw| zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety|;   for \$i (1..999) { \$x= num2en(\$i); \$x=~s/[\s\-]//g; \$l+= length(\$x); } print "Answer to PE17 = ",\$l+length('onethousand');   sub num2en { my(\$x) = \$_[0]; return \$D{\$x} if defined \$D{\$x}; return \$D{\$1 . '0'} . '-' . \$D{\$2} if( \$x =~ m/^(.)(.)\$/ ); if ( \$x =~ m/^(.)(..)\$/ ) { my(\$h, \$rest) = ("\$D{\$1} hundred", \$2); return \$h if \$rest eq '00'; return "\$h and " . num2en(\$rest); } }```

## Discussion

### 2 Responses to “Project Euler 17”

1. dude when u try to print every number you can see that it doesn’t print “s” letters for example not seven but even. Check it out

Posted by ddorian | February 5, 2011, 3:11 PM
• You’re awesome Dorian! The backslashes got removed during publishing. I’ve corrected it. So the corrected line should read:

\$x=num2en(\$i); \$x=~s/[\s\-]//g;

Thanks for being so observant.

Posted by Mike | February 5, 2011, 4:08 PM