Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Algorithm to find unique prime factors #9935

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions maths/prime_factors.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,50 @@ def prime_factors(n: int) -> list[int]:
return factors


def unique_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)
[]
>>> x = unique_prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2, 5]
True
>>> 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 = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if i not in factors:
factors.append(i)
if n > 1:
if n not in factors:
factors.append(n)
return factors


if __name__ == "__main__":
import doctest

Expand Down