A good deterministic way to find relatively small prime numbers is to use a sieve.
The mathematical principle behind this technique is the following: to check if a number is prime, it is sufficient to check that it is not divisible by other primes.
import math
def is_prime(n):
# Prepare our Sieve, for readability we make index match the number by adding 0 and 1
primes = [False] * 2 + [True] * (n - 1)
# Remove non-primes
for x in range(2, int(math.sqrt(n) + 1)):
if primes[x]:
primes[2*x::x] = [False] * (n // x - 1)
return primes[n]
# Or use the following to return all primes:
# return {x for x, is_prime in enumerate(primes) if is_prime}
print(is_prime(13)) # True
For reusability your could adapt the above code to return the set
of all prime numbers up to n
.