-
Notifications
You must be signed in to change notification settings - Fork 80
/
prime.py
78 lines (55 loc) · 1.46 KB
/
prime.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
# Prime Factorization
# Have the user enter a number
# and return its prime factors
# Extra: show the exponent of
# the prime factors as well
from collections import Counter
def is_prime(x):
"""
Checks whether the given
number x is prime or not
"""
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True
def get_exponent(n):
"""
Counts the same elements in n list
returns a list with the exponent of
the multiple elements
"""
c = Counter(n)
factors = []
for i in range(min(n), max(n) + 1):
if i in n:
if c[i] != 1:
factors.append(str(i) + '^' + str(c[i]))
else:
factors.append(str(i))
return factors
def main(): # Wrapper function
n = int(input('Enter a number to find its prime factors: '))
factors = []
counter = 2
while True:
if n == 0 or n == 1:
break
for i in range(counter, n + 1):
if n % i == 0:
if is_prime(i):
factors.append(i)
n //= i
break
if len(factors) != 0:
factors = get_exponent(factors)
print(', '.join(factors))
else:
print('The number', n, 'does not have any prime factors.')
if __name__ == '__main__':
main()