首页 > 解决方案 > 数字因式分解

问题描述

任务是编写将数字折叠成素数的函数。通过给定数字“n”,此函数应返回元组列表p_i,c^i,例如,如果输入为 100,则输出为 (2,2),(5,2)。所以,这是我尝试编写它的方式:

def factor(n):
c = 1
pre_ans = list()
temp_n=n
for i in range(2,temp_n+1):
    if (is_prime(i) == True) and (temp_n % i == 0):
        for j in range (2,temp_n+1):
            if (temp_n % (i ** j) == 0):
                pre_ans.append((i,j))
                temp_n /= (i **j)
        pre_ans.append((i,c))
        temp_n /= i
print(pre_ans)

它工作错了,但我找不到错误:(

标签: pythonpython-3.xprimesfactorization

解决方案


你的总体思路没问题。但是,您的代码的以下部分存在一些小问题:

for j in range (2,temp_n+1):
    if (temp_n % (i ** j) == 0):
        pre_ans.append((i,j))
        temp_n /= (i **j)
pre_ans.append((i,c))
temp_n /= i

事实上,主要问题是您需要在此语句的另一个方向上进行迭代for j in range (2,temp_n+1)。如果你像这样重写它

def factor(n):
    c = 1
    pre_ans = list()
    temp_n=n
    for i in range(2,temp_n+1):
        if (is_prime(i) == True) and (temp_n % i == 0):
            for j in range (temp_n+1, 0,-1):
                if (temp_n % (i ** j) == 0):
                    pre_ans.append((i,j))
                    temp_n /= (i **j)
    print(pre_ans)

它会起作用的。整个代码也可以写得更短一些:

from collections import Counter

def factor(n):
    lst = []
    for i in range(2, n+1):
        while n % i == 0:
            lst.append(i)
            n = n / i
    return Counter(lst).items()

print(factor(100))

推荐阅读