MCPcopy
hub / github.com/TheAlgorithms/Python / prime_factorization

Function prime_factorization

maths/primelib.py:179–229  ·  view source on GitHub ↗

input: positive integer 'number' returns a list of the prime number factors of 'number' >>> prime_factorization(0) [0] >>> prime_factorization(8) [2, 2, 2] >>> prime_factorization(287) [7, 41] >>> prime_factorization(-1) Traceback (most recent call last):

(number)

Source from the content-addressed store, hash-verified

177
178
179def prime_factorization(number):
180 """
181 input: positive integer 'number'
182 returns a list of the prime number factors of 'number'
183
184 >>> prime_factorization(0)
185 [0]
186 >>> prime_factorization(8)
187 [2, 2, 2]
188 >>> prime_factorization(287)
189 [7, 41]
190 >>> prime_factorization(-1)
191 Traceback (most recent call last):
192 ...
193 AssertionError: 'number' must been an int and >= 0
194 >>> prime_factorization("test")
195 Traceback (most recent call last):
196 ...
197 AssertionError: 'number' must been an int and >= 0
198 """
199
200 # precondition
201 assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
202
203 ans = [] # this list will be returns of the function.
204
205 # potential prime number factors.
206
207 factor = 2
208
209 quotient = number
210
211 if number in {0, 1}:
212 ans.append(number)
213
214 # if 'number' not prime then builds the prime factorization of 'number'
215 elif not is_prime(number):
216 while quotient != 1:
217 if is_prime(factor) and (quotient % factor == 0):
218 ans.append(factor)
219 quotient /= factor
220 else:
221 factor += 1
222
223 else:
224 ans.append(number)
225
226 # precondition
227 assert isinstance(ans, list), "'ans' must been from type list"
228
229 return ans
230
231
232# -----------------------------------------

Callers 3

greatest_prime_factorFunction · 0.85
smallest_prime_factorFunction · 0.85
kg_vFunction · 0.85

Calls 2

is_primeFunction · 0.70
appendMethod · 0.45

Tested by

no test coverage detected