Hi everyone,
I have a problem with one of the problems (17) that i try to solve on the Project Euler site.
The problem is as follows:
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 code that i have written is as follows:
<?php
function decimal($i)
{
if ($i == 1)
{
return 3;
}
elseif ($i == 5 || $i == 6 || $i == 4)
{
return 5;
}
elseif ($i == 7)
{
return 7;
}
else
{
return 6;
}
}
function onedigit($i)
{
if ($i == 1 || $i == 2 || $i == 6)
{
return 3;
}
elseif ($i == 4 || $i == 5 || $i == 9)
{
return 4;
}
elseif ($i == 0)
{
return 0;
}
else
{
return 5;
}
}
function twodigit($i)
{
if ($i == 14 || $i == 16 || $i == 17 || $i == 19)
{
if ($i == 16)
{
return 7;
}
elseif ($i == 17)
{
return 9;
}
else
{
return 8;
}
}
else
{
return onedigit(substr($i,1,1))+decimal(substr($i,0,1));
}
}
function threedigit($i)
{
if (substr($i,1,1) != 0 && substr($i,2,1) != 0)
return onedigit(substr($i,0,1))+10+twodigit(substr($i,1,2));
elseif (substr($i,1,1) == 0 && substr($i,2,1) != 0)
return onedigit(substr($i,0,1))+10+onedigit(substr($i,2,1));
else
return onedigit(substr($i,0,1))+7;
}
$length=0;
$limit=999;
for ($i=1; $i<$limit+1; $i++)
{
if (strlen($i) == 1)
$length += onedigit($i);
elseif (strlen($i) == 2)
$length += twodigit($i);
else
$length += threedigit($i);
}
echo $length+11;//Here i add "One thousand"
?>
I really don't know where i have made a mistake but i know from a friend that the good result should be: 21124
If someone can find my mistake, it would be usefull for me.
Thanks in advance,
Olivier