我正在寻找帮助编写一个函数,它接受一个正整数n作为输入,并将它的素因式分解打印到屏幕上。输出应将这些因素集合到单个字符串中,以便像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,则输出为“60 =2x2x3x5”
发布于 2021-02-11 14:04:51
使用列表存储所有因子,然后将它们一起以所需的格式打印为字符串。
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)发布于 2021-02-11 14:31:09
这是一种使用f-string来完成此操作的方法。此外,你需要做整数除法(用//),以避免在你的答案中得到浮点数。
""""
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发布于 2021-02-13 23:34:06
您应该始终将计算与表示分开。您可以将该函数构建为一个生成器,该生成器通过增加除数(2,然后是赔率)来除数。当你找到一个合适的,输出它并继续除法的结果。这只会产生质数因子。
然后使用该函数获取要打印的数据,而不是尝试混合打印和格式化。
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输出:
N=60
print(N,end=" = ")
print(*primeFactors(N),sep=" x ")
60 = 2 x 2 x 3 x 5https://stackoverflow.com/questions/66148587
复制相似问题