【发布时间】:2021-05-14 19:56:42
【问题描述】:
我正在寻求帮助编写一个函数,该函数将正整数 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 = 2 x 2 x 3 x 5”
【问题讨论】:
-
My post here 展示了一种使用 sympy 库的方法,除非您想自己动手。
-
你试过这样打印吗?你遇到了什么问题?
-
程序打印以下内容:2 2 3 5.0 我不知道如何让它打印这样的字符串:'60 = 2 x 2 x 3 x 5'
-
你知道如何使用列表吗?你知道如何操作字符串吗?
标签: python python-3.x jupyter-notebook jupyter