-
Notifications
You must be signed in to change notification settings - Fork 0
/
factors
executable file
·73 lines (62 loc) · 2.09 KB
/
factors
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
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/python3
import sys
from random import randint
def gcd(a, b):
"""
Compute the greatest common divisor of a and b.
Parameters:
a, b (int): Two integers for which the GCD needs to be computed.
Returns:
int: The greatest common divisor of a and b.
"""
while b != 0:
a, b = b, a % b
return a
def pollards_rho(n, max_iterations=1000):
"""
Implement the Pollard's Rho algorithm for factorization of numbers. This algorithm is
an efficient semi-probabilistic factorization algorithm which returns one factor of the
number. This factor can be a prime number or a composite number. The algorithm works
by defining a pseudo-random sequence and then using Floyd's cycle detection algorithm
to find a non-trivial divisor.
Parameters:
n (int): The integer to be factorized.
max_iterations (int): The maximum number of iterations before the algorithm restarts with new random values.
Returns:
int: A factor of the integer n.
"""
if n % 2 == 0:
return 2
for _ in range(max_iterations):
x = randint(1, n-1)
y = x
c = randint(1, n-1)
g = 1
while g==1:
x = ((x * x) % n + c) % n
y = ((y * y) % n + c) % n
y = ((y * y) % n + c) % n
g = gcd(abs(x-y), n)
if g != n:
return g
return n
def main():
"""
Main function to handle the input/output and call the factorization function.
It reads numbers from a file given as command line argument, and prints their factorization.
The factorization is done using the Pollard's Rho algorithm.
Command line arguments:
1. Name of the file containing the integers to be factorized. The file should contain
one integer per line.
"""
if len(sys.argv) != 2:
print("Usage: factors <file>")
return
with open(sys.argv[1], 'r') as file:
for line in file:
n = int(line.strip())
p = pollards_rho(n)
q = n // p
print("{}={}*{}".format(n, p, q))
if __name__ == "__main__":
main()