Fortran Implementation of Problem 17
View source code here on GitHub!
- integer Problem0017/p0017()
1! Project Euler Problem 17
2!
3! The key here was remembering I don't need to return the whole string, just the length
4!
5! Problem:
6!
7! If the numbers 1 to 5 are written out in words: one, two, three, four, five,
8! then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
9!
10! If all the numbers from 1 to 1000 (one thousand) inclusive were written out in
11! words, how many letters would be used?
12!
13! NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
14! forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20
15! letters. The use of "and" when writing out numbers is in compliance with
16! British usage.
17
18module Problem0017
19 implicit none
20contains
21 pure integer recursive function to_string_len(n) result(answer)
22 integer, intent(in) :: n
23 integer :: tmp
24 answer = 0
25 if (n >= 1000) then
26 answer = to_string_len(mod(n / 1000, 100)) + 8
27 tmp = mod(n, 1000)
28 if (tmp /= 0) then
29 answer = answer + to_string_len(tmp)
30 end if
31
32 elseif (n >= 100) then
33 answer = to_string_len(mod(n / 100, 10)) + 7
34 tmp = mod(n, 100)
35 if (tmp /= 0) then
36 answer = answer + 3 + to_string_len(tmp)
37 end if
38
39 elseif (n >= 20) then
40 select case (n / 10)
41 case (4, 5, 6)
42 answer = 5
43 case (2, 3, 8, 9)
44 answer = 6
45 case (7)
46 answer = 7
47 end select
48
49 tmp = mod(n, 10)
50 if (tmp /= 0) then
51 answer = answer + to_string_len(tmp)
52 end if
53
54 else
55 select case (n)
56 case (1, 2, 6, 10)
57 answer = 3
58 case (0, 4, 5, 9)
59 answer = 4
60 case (3, 7, 8)
61 answer = 5
62 case (11, 12)
63 answer = 6
64 case (15, 16)
65 answer = 7
66 case (13, 14, 18, 19)
67 answer = 8
68 case (17)
69 answer = 9
70 end select
71 end if
72 end function
73
74 pure integer function p0017() result(answer)
75 integer :: x
76
77 answer = 0
78 do x = 1, 1000
79 answer = answer + to_string_len(x)
80 end do
81 end function p0017
82end module Problem0017