Lua Implementation of Problem 34

View source code here on GitHub!

Includes

Solution

solution()
Returns:

The solution to problem 34

Return type:

number

 1-- Project Euler Problem 34
 2--
 3-- This ended up being a filtering problem. The problem with my solution is that I
 4-- am not satisfied with my filter at all. I feel like there is a more efficient
 5-- way to go about it.
 6--
 7-- Problem:
 8--
 9-- 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
10--
11-- Find the sum of all numbers which are equal to the sum of the factorial of
12-- their digits.
13--
14-- Note: as 1! = 1 and 2! = 2 are not sums they are not included.
15
16local factorial = loadlib('math').factorial
17
18return {
19    solution = function()
20        local answer = 0
21
22        for x = 10,99999 do
23            local xs = tostring(x)
24            local sum = 0
25            for i = 1,#xs do
26                sum = sum + factorial(tonumber(xs:sub(i, i)))
27            end
28
29            if sum == x then
30                answer = answer + x
31            end
32        end
33
34        return answer
35    end
36}

Tags: factorial, digit-sum