Added solution for problem 35

This commit is contained in:
2021-06-06 12:19:13 -04:00
parent acdb66560d
commit 3e191e9d74

82
Problem35.lua Normal file
View File

@@ -0,0 +1,82 @@
--ProjectEuler/ProjectEulerLua/Problem35.lua
--Matthew Ellison
-- Created: 06-05-21
--Modified: 06-05-21
--How many circular primes are there below one million?
--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 we are checking for primes
local primes = {}; --The primes below MAX_NUM
local circularPrimes = {}; --The circular primes below MAX_NUM
--Functions
--Returns a list of all rotations of a string passed to it
local function getRotations(str)
local rotations = {};
table.insert(rotations, str);
for cnt = 1, string.len(str) - 1 do
str = string.sub(str, 2) .. string.sub(str, 1, 1);
table.insert(rotations, str);
end
return rotations;
end
--Start the timer
timer:start();
--Get all primes under 1,000,000
primes = getPrimes(MAX_NUM);
--Go through all primes, get all their rotations, and check if those numbers are also primes
for cnt = 1, #primes do
local prime = primes[cnt];
local allRotationsPrime = true;
--Get all of the rotations of the prime and see if they are also prime
local rotations = getRotations(tostring(prime));
for rotCnt = 1, #rotations do
local rotation = rotations[rotCnt];
local p = tonumber(rotation, 10);
if(not isFound(primes, p)) then
allRotationsPrime = false;
break;
end
end
--If all rotations are prime add it to the list of circular primes
if(allRotationsPrime) then
table.insert(circularPrimes, prime);
end
end
--Stop the timer
timer:stop();
--Print the results
io.write("The number of all circular prime numbers under " .. MAX_NUM .. " is " .. #circularPrimes .. "\n");
io.write("It took " .. timer:getString() .. " to run this algorithm\n");
--[[ Results:
The number of all circular prime numbers under 999999 is 55
It took 102.268 seconds to run this algorithm
]]