Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ssanin82/18582bf4a1849dfb8afd to your computer and use it in GitHub Desktop.
Save ssanin82/18582bf4a1849dfb8afd to your computer and use it in GitHub Desktop.
import random
def gcd(a, b):
a = abs(a)
b = abs(b)
while a:
a, b = b % a, a
return b
def brent(N):
if N % 2 == 0:
return 2
y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)
g, r, q = 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = ((y * y) % N + c) % N
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = ((y * y) % N + c) % N
q = q * (abs(x - y)) % N
g = gcd(q, N)
k = k + m
r *= 2
if g == N:
while True:
ys = ((ys * ys) % N + c) % N
g = gcd(abs(x - ys), N)
if g > 1:
break
return g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment