此文為延續 Python 找質數 一文,在解此題之前,請先看質因數分解的影片講解。
要解這題,有幾種作法:
方法一:
1. 除數從 2 開始,若此被除數可以被除數 2 整除,就被除數就一直除以 2;若不行除數換用 3。
2. 一直重複到 除數的平方大於或小於 被除數。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def prime_factoring(n): | |
divisor = 2 | |
factors = [] | |
while divisor * divisor <= n: | |
if n % divisor: | |
divisor += 1 | |
else: | |
n //= divisor | |
factors.append(divisor) | |
if n > 1: | |
factors.append(n) | |
return factors | |
aNumber = (int)(input("Enter a number:")); | |
print(prime_factoring(aNumber)); |
方法二:
1. 求出小於此被除數開根號後的所有質數。
2. 在用這些質數去除被除數算出每個質因數出現的次數。
2. 在用這些質數去除被除數算出每個質因數出現的次數。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math; | |
def eratosthenes(n): | |
P = [i for i in range(2, (int)(math.sqrt(n)+1))] | |
p = 0 | |
while True: | |
for i in P[p + 1:]: | |
if i % P[p] == 0: | |
P.remove(i) | |
if P[p]**2 >= P[-1]: | |
break | |
p += 1 | |
return P | |
aNumber = (int)(input("Enter a number:")); | |
factors = eratosthenes(aNumber); | |
num = aNumber; | |
for divisor in factors: | |
while( num % divisor == 0 ): | |
num //= divisor | |
print(divisor, ' ', end = ''); |
方法二好像不怎麼好XD。
除了以上方法外,讀者您還有想到什麼方法呢?
除了以上方法外,讀者您還有想到什麼方法呢?