-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathfactor.py
61 lines (54 loc) · 1.38 KB
/
factor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#coding: utf-8
''' mbinary
#######################################################################
# File : factorize.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-16 09:36
# Description: factorization, using pollard's rho algorithm and miller-rabin primality test
#######################################################################
'''
from random import randint
from isPrime import isPrime
from gcd import gcd
def factor(n):
'''pollard's rho algorithm'''
if n < 1:
raise Exception('[Error]: {} is less than 1'.format(n))
if n == 1:
return []
if isPrime(n):
return [n]
fact = 1
cycle_size = 2
x = x_fixed = 2
c = randint(1, n)
while fact == 1:
for i in range(cycle_size):
if fact > 1:
break
x = (x*x+c) % n
if x == x_fixed:
c = randint(1, n)
continue
fact = gcd(x-x_fixed, n)
cycle_size *= 2
x_fixed = x
return factor(fact)+factor(n//fact)
def fact(n):
f = 2
ret = []
while f*f <= n:
while not n % f:
ret.append(f)
n//f
f += 1
if n > 1:
ret.append(n)
return ret
if __name__ == '__main__':
while 1:
n = int(input('n: '))
print(factor(n))