Skip to content

Commit c1a2954

Browse files
committed
Improve Fermat attack algorithm by replacing isqrt with isqrt_rem and is_square.
1 parent 2c439f5 commit c1a2954

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

fermat.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
import sys
2-
from gmpy2 import isqrt
2+
from gmpy2 import isqrt, isqrt_rem, is_square
33

44
def fermat(n):
5-
"""Fermat attack"""
6-
a = isqrt(n)
7-
a = b
8-
b2 = (a ** 2) - n
9-
count = 0
10-
while (b ** 2) != b2:
11-
a = a + 1
12-
b2 = (a ** 2) - n
13-
b = isqrt(b2)
14-
count += 1
15-
p = a + b
16-
q = a - b
17-
assert n == p * q
18-
return p, q
5+
a, rem = isqrt_rem(n)
6+
b2 = -rem
7+
c0 = (a << 1) + 1
8+
c = c0
9+
while not is_square(b2):
10+
b2 += c
11+
c += 2
12+
a = (c - 1) >> 1
13+
b = isqrt(b2)
14+
return a - b, a + b
1915

2016
print(fermat(int(sys.argv[1])))

0 commit comments

Comments
 (0)