Skip to content

Commit 311baf0

Browse files
committed
fix miller_rabin
1 parent fffe5f0 commit 311baf0

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

cyaron/math.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def is_prime(n):
140140

141141

142142
#--- Miller-Rabin primality test----------------------------------------------------------------
143-
def miller_rabin(n):
143+
def miller_rabin(n, repeat_time=20):
144144
"""
145145
Check n for primalty: Example:
146146
@@ -150,15 +150,19 @@ def miller_rabin(n):
150150
Algorithm & Python source:
151151
http://en.literateprograms.org/Miller-Rabin_primality_test_(Python)
152152
"""
153+
if (n & 1) == 0 or n < 3:
154+
return n == 2
155+
if (n % 3) == 0:
156+
return n == 3
153157
d = n - 1
154158
s = 0
155-
while d % 2 == 0:
159+
while (d & 1) == 0:
156160
d >>= 1
157161
s += 1
158-
for repeat in range(20):
162+
for _ in range(repeat_time):
159163
a = 0
160164
while a == 0:
161-
a = random.randrange(n)
165+
a = random.randint(2, n)
162166
if not miller_rabin_pass(a, s, d, n):
163167
return False
164168
return True
@@ -167,7 +171,7 @@ def miller_rabin_pass(a, s, d, n):
167171
a_to_power = pow(a, d, n)
168172
if a_to_power == 1:
169173
return True
170-
for i in range(s-1):
174+
for _ in range(s-1):
171175
if a_to_power == n - 1:
172176
return True
173177
a_to_power = (a_to_power * a_to_power) % n

0 commit comments

Comments
 (0)