版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanchunhui/article/details/81517109
Efficient program to print all prime factors of a given number
import math
def number_factorize(num):
prime_factors = []
# 如果整数为偶数,其素因子为 2 的个数;
while num % 2 == 0:
prime_factors.append(2)
num //= 2
num_square_root = int(math.sqrt(num)) + 1
# 3,5,7,9,11,13,15...
for i in range(3, num_square_root, 2):
# 提前终止
if num < 2:
return prime_factors
# 9=3*3,15=3*5,
while num % i == 0:
# i=9,不会进入while循环,9 的素因子是 3*3,会在 i=3 时分解掉;
prime_factors.append(i)
num //= i
# 如果该数本身即为素数,如 17,不会参与前面的流程
if num > 2:
prime_factors.append(num)
return prime_factors
if __name__ == '__main__':
print(number_factorize(315))