Skip to content

Commit a2c0e18

Browse files
committed
Add functions to find next and previous prime numbers, and generate random primes within a range
1 parent 5116d54 commit a2c0e18

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

cyaron/math.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,3 +549,94 @@ def n2words(num: int, join: bool = True):
549549
if join:
550550
return ' '.join(words)
551551
return words
552+
553+
554+
def nextprime(n: int):
555+
"""
556+
Find the next prime number after a given number.
557+
Args:
558+
n: The number after which to find the next prime.
559+
Returns:
560+
The next prime number after n.
561+
"""
562+
563+
if n < 2:
564+
return 2
565+
if n == 2:
566+
return 3
567+
if n % 6 == 0:
568+
if miller_rabin(n + 1):
569+
return n + 1
570+
n += 6
571+
elif 1 <= n % 6 < 5:
572+
n += 6 - n % 6
573+
else:
574+
if miller_rabin(n + 2):
575+
return n + 2
576+
n += 7
577+
while True:
578+
if miller_rabin(n - 1):
579+
return n - 1
580+
if miller_rabin(n + 1):
581+
return n + 1
582+
n += 6
583+
584+
585+
def prevprime(n: int, raise_error: bool = True):
586+
"""
587+
Find the previous prime number before a given number.
588+
Args:
589+
n: The number before which to find the previous prime.
590+
raise_error: Raise an error if there is no prime number less than `n`. Default is True.
591+
Returns:
592+
The previous prime number before `n`.
593+
Raises:
594+
ValueError: If there is no prime number less than `n` and `raise_error` is True.
595+
"""
596+
if n <= 2:
597+
if raise_error:
598+
raise ValueError(f"No prime number less than {n}")
599+
return 0
600+
if n == 3:
601+
return 2
602+
if n <= 5:
603+
return 3
604+
if n % 6 == 0:
605+
if miller_rabin(n - 1):
606+
return n - 1
607+
n -= 6
608+
elif n % 6 == 1:
609+
if miller_rabin(n - 2):
610+
return n - 2
611+
n -= 7
612+
else:
613+
n -= n % 6
614+
while True:
615+
if miller_rabin(n + 1):
616+
return n + 1
617+
if miller_rabin(n - 1):
618+
return n - 1
619+
n -= 6
620+
621+
622+
def randprime(a: int, b: int, raise_error: bool = True):
623+
"""
624+
Generate a random prime number in the range [a, b].
625+
Args:
626+
a: The lower bound of the range.
627+
b: The upper bound of the range.
628+
Returns:
629+
A random prime number in the specified range.
630+
"""
631+
st = random.randint(a, b)
632+
if miller_rabin(st):
633+
return st
634+
nxt = nextprime(st)
635+
if nxt <= b:
636+
return nxt
637+
pre = prevprime(st)
638+
if pre >= a:
639+
return pre
640+
if raise_error:
641+
raise ValueError(f"No prime number in the range [{a}, {b}]")
642+
return 0

0 commit comments

Comments
 (0)