2019-07-10 20:09:24 +00:00
|
|
|
"""Prime Check."""
|
|
|
|
|
2018-10-28 11:23:56 +00:00
|
|
|
import math
|
2019-05-11 11:20:25 +00:00
|
|
|
import unittest
|
|
|
|
|
|
|
|
|
2020-08-29 15:11:02 +00:00
|
|
|
def prime_check(number: int) -> bool:
|
2021-10-22 17:14:27 +00:00
|
|
|
"""Checks to see if a number is a prime in O(sqrt(n)).
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2020-10-23 16:17:29 +00:00
|
|
|
A number is prime if it has exactly two factors: 1 and itself.
|
2021-10-22 17:14:27 +00:00
|
|
|
|
|
|
|
>>> prime_check(0)
|
|
|
|
False
|
|
|
|
>>> prime_check(1)
|
|
|
|
False
|
|
|
|
>>> prime_check(2)
|
|
|
|
True
|
|
|
|
>>> prime_check(3)
|
|
|
|
True
|
|
|
|
>>> prime_check(27)
|
|
|
|
False
|
|
|
|
>>> prime_check(87)
|
|
|
|
False
|
|
|
|
>>> prime_check(563)
|
|
|
|
True
|
|
|
|
>>> prime_check(2999)
|
|
|
|
True
|
|
|
|
>>> prime_check(67483)
|
|
|
|
False
|
2019-05-11 11:20:25 +00:00
|
|
|
"""
|
2020-10-23 16:17:29 +00:00
|
|
|
|
|
|
|
if 1 < number < 4:
|
2019-05-11 11:20:25 +00:00
|
|
|
# 2 and 3 are primes
|
|
|
|
return True
|
2020-10-23 16:17:29 +00:00
|
|
|
elif number < 2 or not number % 2:
|
|
|
|
# Negatives, 0, 1 and all even numbers are not primes
|
2019-05-11 11:20:25 +00:00
|
|
|
return False
|
|
|
|
|
2020-10-23 16:17:29 +00:00
|
|
|
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
|
|
|
|
return not any(not number % i for i in odd_numbers)
|
2019-05-11 11:20:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Test(unittest.TestCase):
|
|
|
|
def test_primes(self):
|
2019-07-10 20:09:24 +00:00
|
|
|
self.assertTrue(prime_check(2))
|
|
|
|
self.assertTrue(prime_check(3))
|
|
|
|
self.assertTrue(prime_check(5))
|
|
|
|
self.assertTrue(prime_check(7))
|
|
|
|
self.assertTrue(prime_check(11))
|
|
|
|
self.assertTrue(prime_check(13))
|
|
|
|
self.assertTrue(prime_check(17))
|
|
|
|
self.assertTrue(prime_check(19))
|
|
|
|
self.assertTrue(prime_check(23))
|
|
|
|
self.assertTrue(prime_check(29))
|
2019-05-11 11:20:25 +00:00
|
|
|
|
|
|
|
def test_not_primes(self):
|
2019-10-05 05:14:13 +00:00
|
|
|
self.assertFalse(
|
2020-10-23 16:17:29 +00:00
|
|
|
prime_check(-19),
|
|
|
|
"Negative numbers are excluded by definition of prime numbers.",
|
|
|
|
)
|
|
|
|
self.assertFalse(
|
|
|
|
prime_check(0),
|
|
|
|
"Zero doesn't have any positive factors, primes must have exactly two.",
|
2019-10-05 05:14:13 +00:00
|
|
|
)
|
|
|
|
self.assertFalse(
|
2020-10-23 16:17:29 +00:00
|
|
|
prime_check(1),
|
|
|
|
"One only has 1 positive factor, primes must have exactly two.",
|
2019-10-05 05:14:13 +00:00
|
|
|
)
|
2019-07-10 20:09:24 +00:00
|
|
|
self.assertFalse(prime_check(2 * 2))
|
|
|
|
self.assertFalse(prime_check(2 * 3))
|
|
|
|
self.assertFalse(prime_check(3 * 3))
|
|
|
|
self.assertFalse(prime_check(3 * 5))
|
|
|
|
self.assertFalse(prime_check(3 * 5 * 7))
|
2018-10-19 17:15:53 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2019-05-11 11:20:25 +00:00
|
|
|
unittest.main()
|