Skip to content

Commit

Permalink
Implementation of wheel factorization.
Browse files Browse the repository at this point in the history
Also, it fixes the bug of skipping the first two numbers after n. For example, in the previous version:

>>> galois.next_prime(100000034)
100000037

>>> galois.next_prime(100000035)
100000039

>>> galois.next_prime(100000036)
100000039

>>> galois.next_prime(100000037)
100000049
  • Loading branch information
avadov committed Nov 30, 2023
1 parent 9b41a86 commit 6e0ea79
Showing 1 changed file with 32 additions and 14 deletions.
46 changes: 32 additions & 14 deletions src/galois/_prime.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,14 +170,23 @@ def prev_prime(n: int) -> int:
if n <= MAX_N:
return PRIMES[bisect.bisect_right(PRIMES, n) - 1]

# TODO: Make this faster using wheel factorization
n = n - 1 if n % 2 == 0 else n # The next possible prime (which is odd)
while True:
n -= 2 # Only check odds
if is_prime(n):
break
shifts = [29, 23, 19, 17, 13, 11, 7, 1] # Factorization wheel for basis {2, 3, 5}
base = n // 30 * 30 # Wheel factorization starting point
found = False # Success flag

while not found:
for shift in shifts:
i = base + shift # May be bigger than n

if i >= n:
continue

if is_prime(i):
found = True
break
base -= 30

return n
return i


@export
Expand Down Expand Up @@ -210,14 +219,23 @@ def next_prime(n: int) -> int:
if n < PRIMES[-1]:
return PRIMES[bisect.bisect_right(PRIMES, n)]

# TODO: Make this faster using wheel factorization
n = n + 1 if n % 2 == 0 else n + 2 # The next possible prime (which is odd)
while True:
n += 2 # Only check odds
if is_prime(n):
break
shifts = [1, 7, 11, 13, 17, 19, 23, 29] # Factorization wheel for basis {2, 3, 5}
base = n // 30 * 30 # Wheel factorization starting point. May be less than n.
found = False # Success flag

while not found:
for shift in shifts:
i = base + shift

if i <= n:
continue

if is_prime(i):
found = True
break
base += 30

return n
return i


@export
Expand Down

0 comments on commit 6e0ea79

Please sign in to comment.