Files
ProjectEulerLua/Problem9.lua

73 lines
2.6 KiB
Lua

--ProjectEuler/lua/Problem9.lua
--Matthew Ellison
-- Created: 02-06-19
--Modified: 06-19-20
--There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
--[[
Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]]
require "Stopwatch"
local timer = Stopwatch:create();
timer:start();
local foundTriplet = false; --A simple flag to determine if we have found what we are looking for
local sideA = 1; --Start with the lowest possible a and search for the b that completes the triplet
local sideB = 0; --Holds the second side of the triangle
local sideC = 0; --Holds the hyp
while((sideA <= (1000 / 3)) and (not foundTriplet)) do
--Setup sides b and c
sideB = sideA + 1;
sideC = math.sqrt(sideA^2 + sideB^2); --Get the hyp
if((sideC % 1) == 0) then --If the hyp is an integer then make it one
sideC = math.floor(sideC);
end
--Loop through all possible b's and calculate c's until you find a number >= 1000
while((sideA + sideB + sideC) < 1000) do
sideB = sideB + 1;
sideC = math.sqrt(sideA^2 + sideB^2); --Get the hyp
if((sideC % 1) == 0) then --If the hyp is an integer then make it one
sideC = math.floor(sideC);
end
end
--Check if the correct sides were found, otherwise continue to the next possible side
if((sideA + sideB + sideC) == 1000) then
foundTriplet = true;
else
sideA = sideA + 1;
end
end
timer:stop();
--Print the results
if(foundTriplet) then
print("The Pythagorean triplet where a + b + c = 1000 is " .. sideA .. ' ' .. sideB .. ' ' .. sideC);
print("The product of those numbers is " .. sideA * sideB * sideC);
else
print("Could not find the Pythagorean triplet where a + b + c = 1000");
end
print("It took " .. timer:getMilliseconds() .. " milliseconds to run this algorithm");
--[[Results
The Pythagorean triplet where a + b + c = 1000 is 200 375 425
The product of those numbers is 31875000
It took 17.104 milliseconds to run this algorithm
]]