Lua Implementation of Problem 9

View source code here on GitHub!

Solution

solution()
Returns:

The solution to problem 9

Return type:

number

 1-- Project Euler Problem 9
 2--
 3-- This was pretty fun to port
 4--
 5-- Problem:
 6--
 7-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
 8-- a**2 + b**2 = c**2
 9--
10-- For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
11--
12-- There exists exactly one Pythagorean triplet for which a + b + c = 1000.
13-- Find the product abc.
14
15return {
16    solution = function()
17        local c = 3
18
19        while true do
20            local c_square = c * c
21
22            for b = 2,c do
23                local b_square = b * b
24
25                for a = 1,b do
26                    local a_square = a * a
27
28                    if a_square + b_square == c_square and a + b + c == 1000 then
29                        return a * b * c
30                    end
31                end
32            end
33            c = c + 1
34        end
35    end
36}

Tags: pythagorean-triple