首页 > 解决方案 > 打印任何数字的素数分解的函数/ Python

问题描述

标签: pythonpython-3.xjupyter-notebookjupyter

解决方案


这是一种使用 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

推荐阅读