Inspired by Project Euler #17, this is your challenge. Write a full program or function that takes a number as input, then print or return how many letters it would take to count up to and including that number in English (starting at one). You do not include spaces, commas, or hyphens, but you should include the word and
. For example. 342 is spelled: Three Hundred and Forty-Two
. This is 23 letters long.
Your input will be a positive integer. You do not have to handle invalid inputs. Built-ins or libraries that convert numbers to English are not allowed.
Here are all of the rules for how to spell numbers. (Note: I realize that some people use a different set of rules for how to spell numbers. This will just be the official rules for the purpose of this challenge)
1 to 20
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty
21 to 99
Join these:
Twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
to these:
-one, -two, -three, -four, -five, -six, -seven, -eight, -nine,
Note that four has a u but forty does not!
Examples:
53: Fifty-three
60: sixty
72: seventy-two
99: ninety-nine
100 to 999
Write out how many hundreds (one hundred, two hundred, three hundred, etc.), an "and", and the rest of the number as above. The and does count towards your letter score.
Examples:
101: One hundred and one
116: One hundred and sixteen
144: One hundred and forty-four
212: Two hundred and twelve
621: Six Hundred and twenty-one
1,000 to 999,999
Write how many thousands (one thousand, two thousand, etc.), a comma, then the rest of the number as above. Note that if you have no hundreds, you still need the and.
Examples:
1,101: One thousand, one hundred and one
15,016: Fifteen thousand and sixteen
362,928: Three hundred and sixty-two thousand, nine hundred and twenty-eight
Millions
Write out how many millions, then the rest of the number as above. Note that "A million" is 6 zeroes "1,000,000".
Examples:
191,232,891: One hundred and ninety-one million, two hundred and thirty-two thousand, eight hundred and ninety-one
1,006,101: One million, six thousand, one hundred and one
The same rule applies to billions, trillions, quadrillions and above, but for the purpose of this challenge, you don't have to handle any number above 999,999,999 (Nine Hundred and ninety-nine million, nine-hundred and ninety-nine thousand, nine hundred and ninety-nine.)
Python solver
Here is a short python script to verify answers:
import en
def get_letter_num(s):
count = 0
for c in s:
if c.isalpha():
count += 1
return count
number = input()
count = 0
for i in xrange(1, number + 1):
count += get_letter_num(en.number.spoken(i))
print count
Note that this usesthe NodeBox linguistics library to convert numbers to English. (yes, I just broke my own rule, but this isn't a competing answer) This is freely available here.
Sample I/O
7: 27
19: 106
72: 583
108: 1000
1337: 31,131
1234567: 63,448,174