我有下面的代码,它打印给定数字的唯一因子组合。 但我没有给出所需的输出。代码如下:
#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中的新手,所以犯了一些愚蠢的错误。请有人帮助我在错误的逻辑中。感谢。
答案 0 :(得分:1)
您是否需要所有可能的数字因素或仅需要素数分解?
如果是前者,你应该能够从后者中舒适地构建它。我衷心鼓励使用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}
然后它只是一个组合问题。
这里有三个组成素数可能会得到所有可能的因素
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)
答案 1 :(得分:0)
我得到的答案如下。我一直在寻找所有因素组合而不是独特的因素。谢谢。
#Python program to print out all ways to multiply smaller integers
#that equal the original number, without repeating sets of factors
def print_factors_list(dividend, factorstring, predivisor):
"""This function takes a number and prints the factors"""
divisor = dividend - 1
#Looping to get the factors
for i in range(divisor, 1, -1 ):
if dividend % i != 0:
continue
if i > predivisor:
continue
#Get the quotient for the multipying number
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 integer"
#Check if the number is 0
elif (x == 0):
print "Enter a positive integer"
#Go to the function print_factors_list for further evaluation
else:
#Print the default factors(the number itself and 1)
print str(x) + "*" + str(1)
print_factors_list(x, "", x )
#Take input from the user
num = int(input("Enter a number: "))
#Call the function with the number given by the user
print_factors(num)