python - 打印任何数字的素数分解的函数/ Python
问题描述
解决方案
这是一种使用 f 字符串的方法。此外,您需要进行整数除法(使用 //)以避免在您的答案中出现浮点数。
""""
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
推荐阅读
- python-3.x - 如何在python中迭代特定值作为其范围的动态嵌套循环?
- html - CSS 中的下拉样式问题
- java - 在java中使用多态对json进行序列化和反序列化时出错
- python - 我如何使用 fastai (kaggle) 保存和加载模型
- python - Transformers Longformer IndexError: index out of range in self
- javascript - Node.js Chart.js 实时图表更新
- spring-boot - SpringBoot + Gradle + Mapstruct 失败,在运行时找不到 bean
- python - Discord 消息获取:int() 的无效文字,基数为 10:'guild id'
- css - 在反应中为蚂蚁设计卡提供边界半径
- c# - 等待和事件处理程序