Skip to content

Commit f8a109c

Browse files
committed
add carmichael integer factorization algorithm
1 parent 05cd52e commit f8a109c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

carmichael.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from gmpy2 import *
2+
3+
def factor(N):
4+
"""
5+
Algorithm described in the wagstaf-joy of factoring book.
6+
"""
7+
f = N1 = N - 1
8+
while f & 1 == 0: f >>= 1
9+
a = 2
10+
while a <= N1:
11+
r1 = powmod(a, f << 1, N)
12+
if r1 == 1:
13+
r = powmod(a, f, N)
14+
p = gcd(r - 1, N)
15+
q = gcd(r + 1, N)
16+
if (q > p > 1): #and (p * q == N):
17+
return factor(p) + factor(q)
18+
a = next_prime(a)
19+
return [N]
20+
21+
def tests():
22+
for n in [561,6601, 8911,23224518901,1901 * 3701,6601 * 8911,52193 * 3701]:
23+
print(n, factor(n))
24+
25+
if __name__ == "__main__":
26+
tests()

0 commit comments

Comments
 (0)