[英]Function that prints prime factorization of any number / Python
我正在尋求幫助編寫一個 function ,它將正 integer n 作為輸入並將其素數分解打印到屏幕上。 output 應該將這些因子聚集到一個字符串中,以便像 prime_factorization(60) 這樣的調用結果會將字符串“60 = 2 x 2 x 3 x 5”
打印到屏幕上。 以下是我到目前為止所擁有的。 更新:我取得了進展並想出了如何找到素因數分解。 但是,我仍然需要幫助以上述正確方式打印它。
""""
Input is a positive integer n
Output is its prime factorization, computed as follows:
"""
import math
def prime_factorization(n):
while (n % 2) == 0:
print(2)
# Turn n into odd number
n = n / 2
for i in range (3, int(math.sqrt(n)) + 1, 2):
while (n % i) == 0:
print(i)
n = n / I
if (n > 2):
print(n)
prime_factorization(60)
請注意,我正在嘗試打印它,因此如果輸入為 60,則 output 讀取“60 = 2 x 2 x 3 x 5”
使用列表存儲所有因子,然后以所需格式將它們一起打印為字符串。
import math
def prime_factorization(n):
factors = [] # to store factors
while (n % 2) == 0:
factors.append(2)
# Turn n into odd number
n = n / 2
for i in range (3, int(math.sqrt(n)) + 1, 2):
while (n % i) == 0:
factors.append(i)
n = n / I
if (n > 2):
factors.append(n)
print(" x ".join(str(i) for i in factors)) # to get the required string
prime_factorization(60)
這是一種使用 f 字符串的方法。 此外,您需要進行 integer 除法(帶 //)以避免在您的答案中出現浮點數。
""""
Input is a positive integer n
Output is its prime factorization, computed as follows:
"""
import math
def prime_factorization(n):
n_copy = n
prime_list = []
while (n % 2) == 0:
prime_list.append(2)
# Turn n into odd number
n = n // 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while (n % i) == 0:
prime_list.append(i)
n = n // i
if (n > 2):
prime_list.append(n)
print(f'{n_copy} =', end = ' ')
for factor in prime_list[:-1]:
print (f'{factor} x', end=' ' )
print(prime_list[-1])
prime_factorization(60)
#output: 60 = 2 x 2 x 3 x 5
您應該始終將計算與表示分開。 您可以構建 function 作為生成器,通過增加除數(2,然后是賠率)來除數。 當你找到一個合適的,output 它並繼續除法的結果。 這只會產生主要因素。
然后使用該 function 獲取要打印的數據,而不是嘗試混合打印和格式化。
def primeFactors(N):
p,i = 2,1 # prime divisor and increment
while p*p<=N: # no need to go beyond √N
while N%p == 0: # if is integer divisor
yield p # output prime divisor
N //= p # remove it from the number
p,i = p+i,2 # advance to next potential divisor 2, 3, 5, ...
if N>1: yield N # remaining value is a prime if not 1
output:
N=60
print(N,end=" = ")
print(*primeFactors(N),sep=" x ")
60 = 2 x 2 x 3 x 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.