File tree Expand file tree Collapse file tree 1 file changed +9
-6
lines changed Expand file tree Collapse file tree 1 file changed +9
-6
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments