Skip to content

Instantly share code, notes, and snippets.

@mdnestor
Last active January 16, 2023 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdnestor/775b69c93f097f60783dfbcba6ad5c65 to your computer and use it in GitHub Desktop.
Save mdnestor/775b69c93f097f60783dfbcba6ad5c65 to your computer and use it in GitHub Desktop.
is_prime function using a prime sieve with runtime of O(sqrt n / log n)
from typing import Optional
def smallest_positive_prime_factor(n: int) -> Optional[int]:
N = abs(n)
if N <= 1:
return None
m = 1 + int(N ** (1 / 2))
checked = {d: False for d in range(2, m)}
for d in range(2, m):
if not checked[d]:
if N % d == 0:
return d
for m in range(1, m // d):
checked[d * m] = True
return N
def is_prime(n: int) -> bool:
return abs(n) == smallest_positive_prime_factor(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment