# Project Euler Problem 17 - Number Letter Counts - solved with R

The 17th Project Euler problem - Number Letter Counts - is stated 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 were written out in words, how many letters would be used?

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.

``````nchars.singles = nchar(c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine"))
nchars.teens = nchar(c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"))
nchars.tens =  nchar(c("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"))

# One, two, three...nine.
nchars.001.009 <- sum(nchars.singles)

# Ten, eleven, twelve...ninteen.
nchars.010.019 <- sum(nchars.teens)

# Twentyone, twentytwo...nintynine.
nchars.020.099 <- 10*sum(nchars.tens) + 8 * nchars.001.009

# One, two, three...ninetynine.
nchars.001.099 <- nchars.001.009 + nchars.010.019 + nchars.020.099

# When counting from 1 - 999 we will say 1-9 a hundred times each
# while quantifying hundreds.
# ONE hundred, ONE hundred and one, ONE hundred and two.
a <- nchars.001.009 * 100

# When counting from 1 - 999 we will count from 1-99 ten times.
b <- nchars.001.099 * 10

# Nine of the numbers will include just "hundred"
# One hundred, two hundred, three hundred...nine hundred.
c <- length(nchars.singles) * nchar("hundred")

# 891 (99*9) of the numbers will include "hundred and".
# One hundred and one, one hundred and two... nine hundred and ninety nine.
d <- 891 * nchar("hundredand")

# ...and finnish with One Thousand.
e <- sum(nchar("onethousand"))

sum <- a+b+c+d+e;
sprintf("Number of letters: %s", sum)``````