首页 > 代码库 > 找出指定数字的所有质因数,比如:90=2*3*3*5。

找出指定数字的所有质因数,比如:90=2*3*3*5。

 1 from math import sqrt
 2 from functools import reduce
 3 from operator import mul
 4 
 5 def is_prime(n):
 6     for k in range(2, int(sqrt(n))+1):
 7         if n % k == 0:
 8             return False
 9     return True
10 
11 def get_prime(num):
12     temp = []
13     for i in range(2, num+1):
14         if num % i == 0 and is_prime(i):
15             temp.append(i)
16     return temp
17 
18 def final_factor(num):
19     prime_factor = get_prime(num)
20     while reduce(mul, prime_factor) < num:
21         mid_calc = reduce(mul, prime_factor)
22         prime_factor.extend(get_prime(num//mid_calc))
23     return sorted(prime_factor)

结果:[2, 3, 3, 5]

找出指定数字的所有质因数,比如:90=2*3*3*5。