For Python中的Prime因子循环

时间:2017-09-26 21:26:46

标签: python-2.7

我试图返回此代码中作为素数的数字因子。例如,如果有人进入n = 55,他们将回到5和11.我相信我的第一部分是正确的检查因素,但不知何故,我不确定我是什么'在检查素数的第二部分中缺少。

当我运行55代码时,我只得到5(缺少11个)。

有人可以帮助我查看我的代码并提供反馈吗?

l = []
primefactors = []

def factor(n):
    count = 0

    print 'These are the factors:'
    for num in range(2,n+1):
        if n%num == 0: #checks that it is a factor
            print num #These are the factors
            l.append(num)

    for i in l: 
        if i == 2 : #checks for two
            primefactors.append(i)

        else:
            for x in range(3,i+1,2): #checks for odd numbers
                if  i%x == 0:
                    count += 1
                    if count == 1:
                        primefactors.append(i)


    print "These are the prime factors:"
    print primefactors

2 个答案:

答案 0 :(得分:0)

你可以通过简单地删除所有不必要的东西来获得所有因素,但这不能保证,这个数字是素数:

l = []
primefactors = []
def factor(n):
    count = 0
    for num in range(2,n+1):
        if n%num == 0 and num != n: #checks that it is a factor
             primefactors.append(num)

    print ("These are the prime factors:")
    print (primefactors)
    del l[:]
    del primefactors[:]

答案 1 :(得分:0)

尝试这个,我添加了一个额外的检查,看看在追加到primefactors列表之前数字是否是素数。

primefactors = []
def factor(number):
  for i in range(2,int(number//2)+1):
    prime = True
    for j in range(2,int(i**.5)+1):
      if i%j == 0:
        prime = False
        break
    if prime and number%i == 0:
      primefactors.append(i)
  print (primefactors)

factor(92)
factor(55)

输出:

[2, 23]
[2, 23, 5, 11]