Lua Implementation of Problem 16

View source code here on GitHub!

solution()
Returns:

The solution to problem 16

Return type:

number

 1-- Project Euler Problem 15
 2--
 3-- Problem:
 4--
 5-- 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
 6--
 7-- What is the sum of the digits of the number 2**1000?
 8
 9return {
10    solution = function()
11        local numbers = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
12        local ten15 = 1000000000000000
13        local power = 1
14        local answer = 0
15
16        for _ = 1,1000 do
17            for i = 1,#numbers do
18                numbers[i] = numbers[i] * 2
19            end
20            for i = 1,(#numbers - 1) do
21                if (numbers[i] > ten15) then
22                    numbers[i + 1] = numbers[i + 1] + math.floor(numbers[i] / ten15)
23                    numbers[i] = numbers[i] % ten15
24                end
25            end
26        end
27        for _ = 1, 18 do
28            for i = 1,#numbers do
29                answer = answer + math.floor(numbers[i] / power) % 10
30            end
31            power = power * 10
32        end
33        return answer
34    end
35}

Tags: large-numbers, digit-sum, power