forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprime_factors.py
More file actions
Latest commit
93 lines (82 loc) · 2.05 KB
/
Copy pathprime_factors.py
File metadata and controls
93 lines (82 loc) · 2.05 KB
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
85
86
87
88
89
90
91
92
93
"""
python/black : True
"""
from __future__ importannotations
defprime_factors(n: int) ->list[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)
[]
>>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2]*241 + [5]*241
True
>>> prime_factors(10**-354)
[]
>>> prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i=2
factors= []
whilei*i<=n:
ifn%i:
i+=1
else:
n//=i
factors.append(i)
ifn>1:
factors.append(n)
returnfactors
defunique_prime_factors(n: int) ->list[int]:
"""
Returns unique prime factors of n as a list.
>>> unique_prime_factors(0)
[]
>>> unique_prime_factors(100)
[2, 5]
>>> unique_prime_factors(2560)
[2, 5]
>>> unique_prime_factors(10**-2)
[]
>>> unique_prime_factors(0.02)
[]
>>> unique_prime_factors(10**241)
[2, 5]
>>> unique_prime_factors(10**-354)
[]
>>> unique_prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> unique_prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i=2
factors= []
whilei*i<=n:
ifnotn%i:
whilenotn%i:
n//=i
factors.append(i)
i+=1
ifn>1:
factors.append(n)
returnfactors
if__name__=="__main__":
importdoctest
doctest.testmod()