-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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