素因实施

时间:2013-02-09 22:18:25

标签: python

下面我附上了我的代码进行素数分解并且它有效。我只是想知道是否有任何方法可以使输出更清晰。我将素数因子添加到列表中,但递归末尾的最终列表包含列表列表,但我只想要一个带数字的列表。

def prime_factor(n):
    list = [] 
    if prime(n)==1:
        list.append(n)
        return list
    else:
        for i in range(2,n):
            if n %i ==0:
                a =prime_factor(i)
                b = prime_factor(n/i)
                list.extend(a)
                list.extend(b)
                return list

def prime(n):
    if n ==2 or n==3:
        return 1
    if n==1:
        return 0
    for i in range(2,n):
        if n%i ==0:
            return 0
            break
        if i ==n-1:
            return 1
            break

1 个答案:

答案 0 :(得分:1)

您可以更轻松地获得素数因素:

def factorize(n):
    factors = []

    p = 2
    while True:
        while(n % p == 0 and n > 0): #while we can divide by smaller number, do so
            factors.append(p)
            n = n / p
        p += 1  #p is not necessary prime, but n%p == 0 only for prime numbers
        if p > n / p:
            break
    if n > 1:
        factors.append(n)
    return factors

print factorize(32*9*11*13*13)

打印

[2,2,2,2,3,3,3,11,13]

您的解决方案可以改进为:

def prime_factor(n):
    list = [] 
    if n==1:
        return [1] #or []?
    else:
        for i in range(2,n+1): #additional improvement could be made here
            if n %i ==0:
                b = prime_factor(n/i)
                list.append(i) #i is always prime in here, you return once first i is found
                list.extend(b)
                return list

(你def prime(n):困惑我,没有必要)