This code seems surprisingly fast at checking if a number is prime.
def is_prime(number: int) -> bool:
"""Checks if a number is prime or not"""
# number must be integer
if type(number) != int:
raise TypeError("Non-integers cannot be tested for primality.")
# negatives aren't prime, 0 and 1 aren't prime either
if number <= 1:
return False
# 2 and 3 are prime
elif number <= 3:
return True
# multiples of 2 and 3 aren't prime
elif number % 2 == 0 or number % 3 == 0:
return False
# only need to check if divisible by potential prime numbers
# all prime numbers are of form 6k +/- 1
# only need to check up to square root of number
for i in range(5, int(number**0.5) + 1, 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
However, is there any way to speed this prime testing up?
return False
in the second to last row. \$\endgroup\$if number <= 1
, so in fact it’s excluding any negative number or 0 and 1 – your comment should make this clear. \$\endgroup\$