From 622cde6bfe978e0cee09750c70e107356a601fc1 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Wed, 30 Jun 2021 18:42:35 -0400 Subject: [PATCH] Added function to test if a number is prime --- Algorithms.py | 11 +++++++++++ TestAlgorithms.py | 27 +++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Algorithms.py b/Algorithms.py index 00a8733..8c110c0 100644 --- a/Algorithms.py +++ b/Algorithms.py @@ -97,6 +97,17 @@ def getNumPrimes(numberOfPrimes: int) -> list: #Return the list with all the prime numbers return primes +#This function determines whether a number is prime +def isPrime(possiblePrime: int) -> bool: + if(possiblePrime <= 3): + return possiblePrime > 1 + elif(((possiblePrime % 2) == 0) or ((possiblePrime % 3) == 0)): + return False + for cnt in range(5, int(math.sqrt(possiblePrime)) + 1, 6): + if(((possiblePrime % cnt) == 0) or ((possiblePrime % (cnt + 2)) == 0)): + return False + return True + #This is a function that returns all the factors of goalNumber def getFactors(goalNumber: int) -> list: prime_factors_list = [] diff --git a/TestAlgorithms.py b/TestAlgorithms.py index 7f037e2..6ce7ad0 100644 --- a/TestAlgorithms.py +++ b/TestAlgorithms.py @@ -42,6 +42,29 @@ class TestAlgorithms(unittest.TestCase): answer = Algorithms.getNumPrimes(numPrimes) #Get the answer from the function self.assertEqual(correctAnswer, answer, "getNumPrimes failed the first test") + #This function tests the isPrime function + def testIsPrime(self): + #Test 1 + num = 2 + correctAnswer = True + answer = Algorithms.isPrime(num) + self.assertEqual(correctAnswer, answer, "isPrime failed the first test") + #Test 2 + num = 97 + correctAnswer = True + answer = Algorithms.isPrime(num) + self.assertEqual(correctAnswer, answer, "isPrime failed the second test") + #Test 3 + num = 1000 + correctAnswer = False + answer = Algorithms.isPrime(num) + self.assertEqual(correctAnswer, answer, "isPrime failed the third test") + #Test 4 + num = 1 + correctAnswer = False + answer = Algorithms.isPrime(num) + self.assertEqual(correctAnswer, answer, "isPrime failed the fourth test") + #This function tests the getFactors function def testGetFactors(self): #Test 1 @@ -203,9 +226,9 @@ if __name__ == "__main__": unittest.main() """Results: -............ +............. ---------------------------------------------------------------------- -Ran 12 tests in 0.002s +Ran 13 tests in 0.002s OK """