Euler-17

https://projecteuler.net/problem=17

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
rm(list=ls(all=TRUE))



a <- c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
b <- c("eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen")

#don't use c as a variable

#this is to concatenate with each tens
d <- c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")

#21, 22, 23, 24, ...29
e <- c(rep("twenty", 10), d)

e

## [1] "twenty" "twenty" "twenty" "twenty" "twenty" "twenty" "twenty"
## [8] "twenty" "twenty" "twenty" "one" "two" "three" "four"
## [15] "five" "six" "seven" "eight" "nine"


#31, 32, 33, ....39
f <- c(rep("thirty", 10), d)
g <- c(rep("forty", 10), d)
h <- c(rep("fifty", 10), d)
i <- c(rep("sixty", 10), d)
j <- c(rep("seventy", 10), d)
k <- c(rep("eighty", 10), d)
l <- c(rep("ninety", 10), d)

#character count for 1 throu 99
through99 <- sum(nchar(c(a,b,e,f,g,h,i,j,k,l)))

through99

## [1] 854


#100, 200,300, ...900
m <- sum(nchar( c(rep("hundred",9),d))) #hundreds

#101-199
n <- sum(nchar(rep("onehundredand",99))) + through99
#201-299 etc.
o <- sum(nchar(rep("twohundredand",99))) + through99
p <- sum(nchar(rep("threehundredand",99))) + through99
q <- sum(nchar(rep("fourhundredand",99))) + through99
r <- sum(nchar(rep("fivehundredand",99))) + through99
s <- sum(nchar(rep("sixhundredand",99))) + through99
t <- sum(nchar(rep("sevenhundredand",99))) + through99
u <- sum(nchar(rep("eighthundredand",99))) + through99
v <- sum(nchar(rep("ninehundredand",99))) + through99
w <- sum(nchar("onethousand"))

results <- sum(through99,m,n,o,p,q,r,s,t,u,v,w)
results

## [1] 21124
Share