Lua Implementation of Problem 20
View source code here on GitHub!
- solution()
- Returns:
The solution to problem 20
- Return type:
number
1-- Project Euler Problem 20
2--
3-- Problem:
4--
5-- n! means n × (n − 1) × ... × 3 × 2 × 1
6--
7-- For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
8-- and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
9--
10-- Find the sum of the digits in the number 100!
11
12return {
13 solution = function()
14 local power = 1
15 local answer = 0
16 local ten16 = 10000000000000000
17 local numbers = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
18 for i = 2,100 do
19 for j = 1,#numbers do
20 numbers[j] = numbers[j] * i
21 end
22 for j = 1,(#numbers - 1) do
23 if (numbers[j] > ten16) then
24 numbers[j + 1] = numbers[j + 1] + math.floor(numbers[j] / ten16)
25 numbers[j] = numbers[j] % ten16
26 end
27 end
28 end
29 for _ = 1,16 do
30 for j = 1,#numbers do
31 answer = answer + math.floor(numbers[j] / power) % 10
32 end
33 power = power * 10
34 end
35 return answer
36 end
37}