Skip to content

Commit 2cd0915

Browse files
committed
Somsuk algorithm
1 parent 0c48a2a commit 2cd0915

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

somsuk.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env python3
2+
# Author Dario Clavijo 2022
3+
4+
from gmpy2 import isqrt, gcd, sqrt, powmod, isqrt_rem, is_square
5+
import random
6+
import time
7+
8+
def fermat(n):
9+
a, rem = isqrt_rem(n)
10+
b2 = -rem
11+
c0 = (a << 1) + 1
12+
c = c0
13+
while not is_square(b2):
14+
b2 += c
15+
c += 2
16+
a = (c - 1) >> 1
17+
b = isqrt(b2)
18+
return a - b, a + b
19+
20+
21+
def somsuk(n):
22+
"""
23+
Implementation based on Kritsanapong Somsuk paper:
24+
The new integer factorization algorithm based on fermat’s
25+
factorization algorithm and euler’s theorem (2020).
26+
ISSN: 2088-8708, DOI: 10.11591/ijece.v10i2.pp1469-1476
27+
"""
28+
u = isqrt(n) << 1
29+
c = n
30+
while gcd(c, n) > 1:
31+
c = random.randrange(2, n - 1)
32+
a = powmod(c, -1, n)
33+
s = powmod(c, 2, n)
34+
phi_aprox = n - u + 1
35+
t = powmod(a, phi_aprox, n)
36+
while True:
37+
if t == 1:
38+
x = u >> 1
39+
y = isqrt(x * x - n)
40+
return x - y, x + y
41+
t = (t*s) % n
42+
u += 2
43+
44+
def timeit(f,n):
45+
t0 = time.time()
46+
r = f(n)
47+
t1 = time.time()
48+
print(str(f).split(" ")[1],"(", n , ") =", r,"time:",round(t1-t0,5))
49+
50+
def test():
51+
timeit(somsuk, 340213)
52+
timeit(fermat, 340213)
53+
timeit(somsuk, 788582867650121563)
54+
timeit(fermat, 788582867650121563)
55+
timeit(somsuk, 1047329636821139813)
56+
timeit(fermat, 1047329636821139813)
57+
58+
if __name__ == "__main__":
59+
test()
60+
61+

0 commit comments

Comments
 (0)