Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0c39e43

Browse files
Mary-0165MaximSmolskiy
andauthored
Algorithm to find unique prime factors (#9935)
* algorithm to find unique prime factors * Update prime_factors.py * Update prime_factors.py * Update prime_factors.py --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent 2fa65c7 commit 0c39e43

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎maths/prime_factors.py

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

4949

50+
def unique_prime_factors(n: int) -> list[int]:
51+
"""
52+
Returns unique prime factors of n as a list.
53+
54+
>>> unique_prime_factors(0)
55+
[]
56+
>>> unique_prime_factors(100)
57+
[2, 5]
58+
>>> unique_prime_factors(2560)
59+
[2, 5]
60+
>>> unique_prime_factors(10**-2)
61+
[]
62+
>>> unique_prime_factors(0.02)
63+
[]
64+
>>> unique_prime_factors(10**241)
65+
[2, 5]
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+
i = 2
78+
factors = []
79+
while i * i <= n:
80+
if not n % i:
81+
while not n % i:
82+
n //= i
83+
factors.append(i)
84+
i += 1
85+
if n > 1:
86+
factors.append(n)
87+
return factors
88+
89+
5090
if __name__ == "__main__":
5191
import doctest
5292

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /