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

Function prime_factors

maths/basic_maths.py:6–31  ·  view source on GitHub ↗

Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_factors(-10) Traceback (most recent call last): ... ValueError

(n: int)

Source from the content-addressed store, hash-verified

4
5
6def prime_factors(n: int) -> list:
7 """Find Prime Factors.
8 >>> prime_factors(100)
9 [2, 2, 5, 5]
10 >>> prime_factors(0)
11 Traceback (most recent call last):
12 ...
13 ValueError: Only positive integers have prime factors
14 >>> prime_factors(-10)
15 Traceback (most recent call last):
16 ...
17 ValueError: Only positive integers have prime factors
18 """
19 if n <= 0:
20 raise ValueError("Only positive integers have prime factors")
21 pf = []
22 while n % 2 == 0:
23 pf.append(2)
24 n = int(n / 2)
25 for i in range(3, int(math.sqrt(n)) + 1, 2):
26 while n % i == 0:
27 pf.append(i)
28 n = int(n / i)
29 if n > 2:
30 pf.append(n)
31 return pf
32
33
34def number_of_divisors(n: int) -> int:

Callers 1

euler_phiFunction · 0.70

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected