mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 09:33:58 -05:00
57 lines
2.0 KiB
Lua
57 lines
2.0 KiB
Lua
--ProjectEuler/lua/Problem4.lua
|
|
--Matthew Ellison
|
|
-- Created: 02-05-19
|
|
--Modified: 06-19-20
|
|
--Find the largest palindrome made from the product of two 3-digit numbers
|
|
--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 palindromes = {}; --Holds all palindromes the program finds
|
|
--Loop through every number 100-999 twice, nested, so you can multiply every number by every other number in the array
|
|
for num1=100,999 do
|
|
for num2=num1,999 do
|
|
local currentNum = num1 * num2;
|
|
--If the number is a palindrome add it to the list of palindromes, otherwise ignore it
|
|
--Using strings makes it easier to determine a palindrome
|
|
if(tostring(currentNum) == string.reverse(tostring(currentNum))) then
|
|
palindromes[#palindromes+1] = currentNum;
|
|
end
|
|
end
|
|
end
|
|
|
|
--Sort the list for neatness
|
|
table.sort(palindromes);
|
|
|
|
timer:stop();
|
|
|
|
--Print the results
|
|
print("The largest palindrome made from the product of two 3-digit numbers is " .. palindromes[#palindromes]);
|
|
print("It took " .. timer:getMilliseconds() .. " milliseconds to run this algorithm");
|
|
|
|
--[[Results:
|
|
The largest palindrome made from the product of two 3-digit numbers is 906609
|
|
It took 268.412 milliseconds to run this algorithm
|
|
]]
|