Added function to test if an integer is prime

This commit is contained in:
2021-06-30 17:29:30 -04:00
parent 75f4441f18
commit e5f9a26dc6
2 changed files with 68 additions and 1 deletions

View File

@@ -119,6 +119,21 @@ function getNumPrimes(numberOfPrimes)
return primes;
end
--This function determines whether the number passed into it is a prime
function isPrime(possiblePrime)
if(possiblePrime <= 3) then
return possiblePrime > 1;
elseif(((possiblePrime % 2) == 0) or ((possiblePrime % 3) == 0)) then
return false;
end
for cnt = 5, math.sqrt(possiblePrime), 6 do
if(((possiblePrime % cnt) == 0) or ((possiblePrime % (cnt + 2)) == 0)) then
return false;
end
end
return true;
end
--This is a function that returns all the factors of goalNumber
function getFactors(goalNumber)
local primes = getPrimes(math.ceil(math.sqrt(goalNumber))); --Get all the primes up the largest possible divisor

View File

@@ -1,7 +1,7 @@
--lua/luaClasses/testAlgorithms.lua
--Mathew Ellison
-- Created: 03-28-19
--Modified: 06-29-21
--Modified: 06-30-21
--This script is used to test the Algorithms script
--[[
Copyright (C) 2021 Matthew Ellison
@@ -64,6 +64,52 @@ local function testGetNumPrimes()
end
end
local function testIsPrime()
local failed = false; --Holds whether a test was failed
--Test 1
local num = 2;
local correctAnswer = true;
local answer = isPrime(num);
--Print an error message if the function returned the wrong answer
if(correctAnswer ~= answer) then
io.write("isPrime failed the first test\n");
failed = true;
end
--Test 2
num = 97;
correctAnswer = true;
answer = isPrime(num);
--Print an error message if the function returned the wrong answer
if(correctAnswer ~= answer) then
io.write("isPrime failed the second test\n");
failed = true;
end
--Test 3
num = 1000;
correctAnswer = false;
answer = isPrime(num);
--Print an error message if the function returned the wrong answer
if(correctAnswer ~= answer) then
io.write("isPrime failed the third test\n");
failed = true;
end
--Test 4
num = 1;
correctAnswer = false;
answer = isPrime(num);
--Print an error message if the function returned the wrong answer
if(correctAnswer ~= answer) then
io.write("isPrime failed the fourth test\n");
failed = true;
end
--Print a message if all of the tests passed
if(not failed) then
io.write("isPrime passed all tests\n");
end
end
local function testGetFactors()
local failed = false; --Holds whether a test was failed
@@ -458,6 +504,12 @@ testGetNumPrimes();
timer:stop();
io.write("It took " .. timer:getString() .. " to run this test\n");
--Test isPrime
timer:start();
testIsPrime();
timer:stop();
io.write("It took " .. timer:getString() .. " to run this test\n");
--Test getFactors
timer:start();
testGetFactors();