algorithm-in-python/math/numberTheory/factor.py

62 lines
1.4 KiB
Python
Raw Normal View History

#coding: utf-8
''' mbinary
#######################################################################
# File : factorize.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# 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
2020-04-15 12:28:20 +08:00
from gcd import gcd
def factor(n):
'''pollard's rho algorithm'''
2020-04-15 12:28:20 +08:00
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
2020-04-15 12:28:20 +08:00
c = randint(1, n)
while fact == 1:
for i in range(cycle_size):
2020-04-15 12:28:20 +08:00
if fact > 1:
break
x = (x*x+c) % n
if x == x_fixed:
c = randint(1, n)
continue
2020-04-15 12:28:20 +08:00
fact = gcd(x-x_fixed, n)
cycle_size *= 2
x_fixed = x
return factor(fact)+factor(n//fact)
2020-04-15 12:28:20 +08:00
def fact(n):
2020-04-15 12:28:20 +08:00
f = 2
ret = []
2020-04-15 12:28:20 +08:00
while f*f <= n:
while not n % f:
ret.append(f)
n//f
2020-04-15 12:28:20 +08:00
f += 1
if n > 1:
ret.append(n)
return ret
2020-04-15 12:28:20 +08:00
if __name__ == '__main__':
while 1:
n = int(input('n: '))
print(factor(n))