Lua Implementation of Problem 2

View source code here on GitHub!

Solution

solution()
Returns:

The solution to problem 2

Return type:

number

 1-- Project Euler Problem 2
 2--
 3-- I modeled this after the C++ solution, because it was by far the simplest
 4--
 5-- Problem:
 6--
 7-- Each new term in the Fibonacci sequence is generated by adding the previous two
 8-- terms. By starting with 1 and 2, the first 10 terms will be:
 9--
10-- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
11--
12-- By considering the terms in the Fibonacci sequence whose values do not exceed
13-- four million, find the sum of the even-valued terms.
14
15return {
16    solution = function()
17        local answer = 0
18        local a = 1
19        local b = 2
20
21        while b < 4000000 do
22            answer = answer + b
23
24            for _ = 1,3 do
25                a, b = b, a + b
26            end
27        end
28
29        return answer
30    end
31}

Tags: divisibility, fibonacci-number