Skip to content

Commit 5efa11a

Browse files
committed
algorithm to find unique prime factors
1 parent 795e97e commit 5efa11a

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

maths/prime_factors.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,50 @@ def prime_factors(n: int) -> list[int]:
4646
return factors
4747

4848

49+
def unique_prime_factors(n: int) -> list[int]:
50+
"""
51+
Returns unique prime factors of n as a list.
52+
53+
>>> unique_prime_factors(0)
54+
[]
55+
>>> unique_prime_factors(100)
56+
[2, 5]
57+
>>> unique_prime_factors(2560)
58+
[2, 5]
59+
>>> unique_prime_factors(10**-2)
60+
[]
61+
>>> unique_prime_factors(0.02)
62+
[]
63+
>>> x = unique_prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
64+
>>> x == [2, 5]
65+
True
66+
>>> unique_prime_factors(10**-354)
67+
[]
68+
>>> unique_prime_factors('hello')
69+
Traceback (most recent call last):
70+
...
71+
TypeError: '<=' not supported between instances of 'int' and 'str'
72+
>>> unique_prime_factors([1,2,'hello'])
73+
Traceback (most recent call last):
74+
...
75+
TypeError: '<=' not supported between instances of 'int' and 'list'
76+
77+
"""
78+
i = 2
79+
factors = []
80+
while i * i <= n:
81+
if n % i:
82+
i += 1
83+
else:
84+
n //= i
85+
if i not in factors:
86+
factors.append(i)
87+
if n > 1:
88+
if n not in factors:
89+
factors.append(n)
90+
return factors
91+
92+
4993
if __name__ == "__main__":
5094
import doctest
5195

0 commit comments

Comments
 (0)