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
|
|
|
|
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
def prime_check(number):
|
2019-05-11 11:20:25 +00:00
|
|
|
"""
|
2019-07-10 20:09:24 +00:00
|
|
|
Check to See if a Number is Prime.
|
|
|
|
|
2019-05-11 11:20:25 +00:00
|
|
|
A number is prime if it has exactly two dividers: 1 and itself.
|
|
|
|
"""
|
|
|
|
if number < 2:
|
|
|
|
# Negatives, 0 and 1 are not primes
|
2018-10-28 11:23:56 +00:00
|
|
|
return False
|
2019-05-11 11:20:25 +00:00
|
|
|
if number < 4:
|
|
|
|
# 2 and 3 are primes
|
|
|
|
return True
|
|
|
|
if number % 2 == 0:
|
|
|
|
# Even values are not primes
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Except 2, all primes are odd. If any odd value divide
|
|
|
|
# the number, then that number is not prime.
|
|
|
|
odd_numbers = range(3, int(math.sqrt(number)) + 1, 2)
|
|
|
|
return not any(number % i == 0 for i in odd_numbers)
|
|
|
|
|
|
|
|
|
|
|
|
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(prime_check(-19), "Negative numbers are not prime.")
|
|
|
|
self.assertFalse(
|
|
|
|
prime_check(0), "Zero doesn't have any divider, primes must have two"
|
|
|
|
)
|
|
|
|
self.assertFalse(
|
|
|
|
prime_check(1), "One just have 1 divider, primes must have two."
|
|
|
|
)
|
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()
|