Python Prime因素

时间:2015-05-10 09:47:15

标签: python primes

我再次陷入困境...... 我想创建一个函数来输出给定数字的所有原始因子。 它已经完成了但是它不会为具有相同原始因子的数字提供正确的因子,例如:20 - 5,2,2 所以我添加了一个while循环,检查所有因子的乘积是否等于我输入的数字。 感谢您的帮助:))

prime_numbers = []

def prime_gen(upper_limit):
    for i in range(2, upper_limit):
        for j in range(2, i):
            if i % j == 0:
                break
        else:
            prime_numbers.append(i)
    return prime_numbers



def list_product(list):
    sum = 1
    for i in list:
        sum *= i
    return sum




prime_factors = []
def prime_factor(number):
    while list_product(prime_factors) != number:    #without the while it checked every factor only once
        for i in reversed(prime_gen(number)):
            while number % i != 0:
                break
            else:
                if i != 1:
                    number /= i
                    prime_factors.append(i)
                    continue
                else:
                    break

prime_factor(20)
print (prime_factors)

2 个答案:

答案 0 :(得分:2)

只需使用for循环,从prime_gen获取素数列表:

def prime_gen(upper_limit):
    prime_numbers = [2]
    for i in range(3, upper_limit,2):
        for j in range(2, i):
            if i % j == 0:
                break
        else:
            prime_numbers.append(i)
    return prime_numbers


def prime_factors(n):
    p_f = []
    for prime in prime_gen(n):
        # while n is divisible keep adding the prime
        while n % prime == 0:
            p_f.append(prime)
            # update n by dividing  by the prime
            n //= prime
    if n > 1:
        p_f.append(n)
    return p_f

print(prime_factors(40))
[2, 2, 2, 5] # ->  2*2*2*5 

如果以40为例:

(40, 2) # first prime 2, 40 is divisible by 2
(20, 2) # 40 //= 2 == 20, 20 is divisible by 2
(10, 2) # 20 //= 2 == 10, 10 is divisible by 2
(5, 5)  # 10 //=2 == 5, 5  is not evenly divisible by 2 or 3 so we get 5

如果您想快速生成素数,可以使用sieve

 from math import sqrt

def sieve_of_eratosthenes(n):
    primes = range(3, n + 1, 2) # primes above 2 must be odd so start at three and increase by 2
    for base in xrange(len(primes)):
        if primes[base] is None:
           continue
        if primes[base] >= sqrt(n): # stop at sqrt of n
            break
        for i in xrange(base + (base + 1) * primes[base], len(primes), primes[base]):
            primes[i] = None
    primes.insert(0,2)
    sieve=filter(None, primes)
    return  sieve

答案 1 :(得分:0)

您获得的错误(TypeError: 'float' object cannot be interpreted as an integer)最终是由此声明引起的:

                number /= i

在Python 3中,/=的结果总是一个浮点数。要执行整数除法(以便number保持整数),请使用:

                number //= i

修复此问题后,您会发现您遇到导致无限循环的逻辑错误。