python - 在 python 中打印数字的唯一因子

标签 python algorithm optimization

<分区>

我有下面的代码,它打印给定数字的唯一因子组合。 但我没有给出所需的输出。代码如下:

#Print the factors list for the given number
def print_factors_list(dividend, factorstring, predivisor):
"""This function takes a number and prints the factors"""
divisor = dividend - 1
for i in range(divisor, 1, -1 ):
    if dividend % i != 0:
        continue

    if i > predivisor:
        continue

    quotient = dividend / i


    if quotient <= i:
        if quotient <= predivisor:
            print factorstring + str(i) + "*" + str(quotient)
    print_factors_list(quotient, str(factorstring) + str(i) + "*", i)
    #Check if the number is greater than 0
    def print_factors(x):
    # Check if the number is greater than 0 
    if (x < 0):
       print "Enter a positive interger"
    #Go to the function print_factors_list for further evaluation
    else:
    print_factors_list(x, str(x) + "*" + str(1) + "\n", x )

    #Take input from the user
    num = int(input("Enter a number: "))
    print_factors(num)

我得到如下输出:

32*1
16*2
32*1
8*4
32*1
8*2*2
32*1
4*4*2
32*1
4*2*2*2
32*1
2*2*2*2*2

我应该得到

 32*1
 16*2
 8*4
 8*2*2
 4*4*2
 4*2*2*2
 2*2*2*2*2

我是 python 的新手,所以犯了一些愚蠢的错误。请有人帮助我在逻辑上出错的地方。谢谢。

最佳答案

您是需要一个数的所有可能因子还是只需要质因数分解?

如果是前者,您应该能够轻松地从后者构建它。我衷心鼓励使用 sympy,Python 的符号数学库。

from sympy import *
primefactors(5551) #provides which primes are included
[7, 13, 61]
factorint(5551) #provides how often each prime occurs
{7: 1, 13: 1, 61: 1}

那么这只是一个组合问题。

另请参阅 Python factorization

下面是三个构成素数得到所有可能因子的情况

prime=6329487
pl=primefactors(prime)
pp=factorint(prime)
for i in xrange(1+pp[pl[0]]):
    for j in xrange(1+pp[pl[1]]):
        for k in xrange(1+pp[pl[2]]):
            print (pl[0]**i)*(pl[1]**j)*(pl[2]**k)

关于python - 在 python 中打印数字的唯一因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665728/

相关文章:

python - 有没有更好的方法来迭代两个列表以查找 python 中项目之间的关系?

python - for 循环不会迭代函数中的字符串,但不会迭代函数 - python 3

java - 时间序列数据 - 计算两组的出现次数

c++ - 如何优化以下公共(public)循环?

Python代码检测OS X El Capitan中的暗模式以更改状态栏菜单图标

php - Levenshtein - 分组酒店名称

c - 找到数组中的最大数

language-agnostic - 适用于噪声环境的简单一维粒子群优化算法

c++ - 哪个更快?函数调用还是条件 if 语句?

python - 在 OpenERP 中调用另一个表单的方法返回值