-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa
executable file
·84 lines (64 loc) · 2.02 KB
/
rsa
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
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/python3
import sys
from typing import Tuple
def calculate_gcd(a: int, b: int) -> int:
"""Calculate the greatest common divisor of two integers."""
while b:
a, b = b, a % b
return a
def pollards_rho_factorization(n: int) -> Tuple[int, int]:
"""
Apply Pollard's rho algorithm to factorize a given integer.
Args:
n (int): The integer to be factorized.
Returns:
Tuple[int, int]: A tuple containing two factors of the input integer.
"""
if n % 2 == 0:
return 2, n // 2
x, y, d = 2, 2, 1
f = lambda x: (x**2 + 1) % n
while d == 1:
x = f(x)
y = f(f(y))
d = calculate_gcd(abs(x - y), n)
return d, n // d
def factorize_number(number: int) -> Tuple[int, int]:
"""
Factorize a given integer into two smaller integers.
Args:
number (int): The integer to be factorized.
Returns:
Tuple[int, int]: A tuple containing two factors of the input integer.
"""
if number <= 1:
return number, 1
else:
return pollards_rho_factorization(number)
def main(filename: str) -> None:
"""
Main function to read numbers from a file and print their factorizations.
Parameters:
filename (str): The name of the file containing natural
numbers to factor.
"""
try:
with open(filename, "r") as file:
for line in file:
current_number = int(line.strip())
factor1, factor2 = factorize_number(current_number)
print(f"{current_number}={factor1}*{factor2}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except ValueError:
print(
"Error: Invalid content in the file. "
+ "Please ensure all lines contain valid natural "
+ "numbers greater than 1."
)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: factors file")
sys.exit(1)
input_filename = sys.argv[1]
main(input_filename)