-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactors
executable file
·60 lines (46 loc) · 1.22 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
#!/usr/bin/python3
"""
Factorize as many numbers as possible into a product of two smaller numbers.
Functions:
find_divisor(num) -> int
factorize()
Usage: ./factors <file>
Where <file> is a file containing natural numbers to factor.
One number per line.
Output format: n=p*q
One factorization per line.
p and q are not always prime numbers.
"""
import sys
def find_divisor(num: int) -> int:
"""
Finds the smallest divisor of a given number.
Args:
num (int): A number to find the smallest divisor for.
Returns:
smallest divisor if found
0 if the number is prime
"""
while num % 2 == 0:
return 2
factor = 3
while factor * factor <= num:
if num % factor == 0:
return factor
else:
factor += 2
return 1
def factorize():
"""
Factorizes as many numbers as possible into
a product of two smaller numbers and print them.
"""
with open(sys.argv[1]) as f:
line = f.readline()
while line != '':
num = int(line)
div = find_divisor(num)
print(f"{num}={num//div}*{div}")
line = f.readline()
if __name__ == "__main__":
factorize()