MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / prime_factors

Function prime_factors

maths/prime_factors.py:8–47  ·  view source on GitHub ↗

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:

(n: int)

Source from the content-addressed store, hash-verified

6
7
8def prime_factors(n: int) -> list[int]:
9 """
10 Returns prime factors of n as a list.
11
12 >>> prime_factors(0)
13 []
14 >>> prime_factors(100)
15 [2, 2, 5, 5]
16 >>> prime_factors(2560)
17 [2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
18 >>> prime_factors(10**-2)
19 []
20 >>> prime_factors(0.02)
21 []
22 >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
23 >>> x == [2]*241 + [5]*241
24 True
25 >>> prime_factors(10**-354)
26 []
27 >>> prime_factors('hello')
28 Traceback (most recent call last):
29 ...
30 TypeError: '<=' not supported between instances of 'int' and 'str'
31 >>> prime_factors([1,2,'hello'])
32 Traceback (most recent call last):
33 ...
34 TypeError: '<=' not supported between instances of 'int' and 'list'
35
36 """
37 i = 2
38 factors = []
39 while i * i <= n:
40 if n % i:
41 i += 1
42 else:
43 n //= i
44 factors.append(i)
45 if n > 1:
46 factors.append(n)
47 return factors
48
49
50def unique_prime_factors(n: int) -> list[int]:

Callers 2

liouville_lambdaFunction · 0.90
mobiusFunction · 0.90

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected