mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 09:33:58 -05:00
65 lines
2.1 KiB
Lua
65 lines
2.1 KiB
Lua
--ProjectEuler/ProjectEulerLua/Problem36.lua
|
|
--Matthew Ellison
|
|
-- Created: 06-29-21
|
|
--Modified: 06-29-21
|
|
--Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
|
|
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
|
|
--[[
|
|
Copyright (C) 2021 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"
|
|
require "Algorithms"
|
|
|
|
|
|
--Setup the variables
|
|
local timer = Stopwatch:create();
|
|
local MAX_NUM = 999999; --The largest number that will be checked
|
|
local palindromes = {}; --All numbers that are palindromes in base 10 and 2
|
|
local sum = 0; --The sum of all elements in the list of palindromes
|
|
|
|
--Start the timer
|
|
timer:start();
|
|
|
|
--Start with 1, check if it is a palindrome in base 10 and 2, and continue to MAX_NUM
|
|
for num = 1, MAX_NUM do
|
|
--Check if num is a palindrome
|
|
if(isPalindrome(tostring(num))) then
|
|
--Convert num to base 2 and see if that is a palindrome
|
|
local binNum = toBin(num);
|
|
if(isPalindrome(binNum)) then
|
|
--Add num to the list of palindromes
|
|
table.insert(palindromes, num);
|
|
end
|
|
end
|
|
end
|
|
--Get the sum of all palindromes in the list
|
|
sum = getSum(palindromes);
|
|
|
|
--Stop the timer
|
|
timer:stop();
|
|
|
|
--Print the results
|
|
io.write("The sum of all base 10 and base 2 palindromic numbers < " .. MAX_NUM .. " is " .. sum .. "\n");
|
|
io.write("It took " .. timer:getString() .. " to run this algorithm\n");
|
|
|
|
|
|
--[[ Results:
|
|
The sum of all base 10 and base 2 palindromic numbers < 999999 is 872187
|
|
It took 377.000 milliseconds to run this algorithm
|
|
]]
|