Lua Implementation of Problem 1

View source code here on GitHub!

Solution

solution()
Returns:

The solution to problem 1

Return type:

number

 1-- Project Euler Question 1
 2--
 3-- I did it the old-fashioned way in this language
 4--
 5-- Revision 1:
 6--
 7-- I found a closed form solution that works in the general case, so it's about an
 8-- order of magnitude faster now.
 9--
10-- Problem:
11--
12-- If we list all the natural numbers below 10 that are multiples of 3 or 5, we
13-- get 3, 5, 6 and 9. The sum of these multiples is 23.
14--
15-- Find the sum of all the multiples of 3 or 5 below 1000.
16
17return {
18    solution = function()
19        local answer = 0
20
21        for i = 3,999,3 do
22            answer = answer + i
23        end
24
25        for i = 5,999,5 do
26            answer = answer + i
27        end
28
29        for i = 15,999,15 do
30            answer = answer - i
31        end
32
33        return answer
34    end
35}

Tags: divisibility