練習:輸入一個整數,印出該整數的質因數。
def prime_factors(n):
factors = []
#2是唯一一個偶數質數,也是最小的質數
while n % 2 == 0:
factors.append(2)
n //= 2
#從3開始處理奇數
factor = 3
while factor * factor <= n:
while n % factor == 0:
factors.append(factor)
n //= factor
factor += 2
# 若n本身是質數,且大於2,則將n加入質因數
if n > 2:
factors.append(n)
return factors
#輸入輸出
number = int(input())
print(prime_factors(number))
input:
42
output:
[2, 3, 7]