Skip to content

Commit 03c4316

Browse files
Merge pull request #133 from weilycoder:dev3
修改 Miller-Rabin 算法
2 parents e355bac + 133ddfa commit 03c4316

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

cyaron/math.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -230,11 +230,12 @@ def is_prime(n: int):
230230
return True
231231

232232

233-
def miller_rabin(n: int):
233+
def miller_rabin(n: int, repeat_time: int = 20):
234234
"""
235235
Check if a number is prime using the Miller-Rabin primality test.
236236
Args:
237237
n: The number to be tested for primality.
238+
repeat_time: The number of iterations to perform. Default is 20.
238239
Returns:
239240
True if n is a probable prime, False if n is composite.
240241
Example:
@@ -247,15 +248,17 @@ def miller_rabin(n: int):
247248
Algorithm & Python source:
248249
http://en.literateprograms.org/Miller-Rabin_primality_test_(Python)
249250
"""
251+
if (n & 1) == 0 or n < 3:
252+
return n == 2
253+
if (n % 3) == 0:
254+
return n == 3
250255
f = n - 1
251256
s = 0
252-
while f % 2 == 0:
257+
while (f & 1) == 0:
253258
f >>= 1
254259
s += 1
255-
for _ in range(20):
256-
a = 0
257-
while a == 0:
258-
a = random.randrange(n)
260+
for _ in range(repeat_time):
261+
a = random.randint(2, n - 1)
259262
if not _miller_rabin_pass(a, s, f, n):
260263
return False
261264
return True

0 commit comments

Comments
 (0)