使用Prime列表进行整数分解(试图找到最快的算法)

时间:2019-06-05 15:00:32

标签: python

from itertools import compress


def prime_number(n):
    sieve = bytearray([True]) * (n//2+1)
    for i in range(1,int(n**0.5)//2+1):
        if sieve[i]:
            sieve[2*i*(i+1)::2*i+1] = bytearray((n//2-2*i*(i+1))//(2*i+1)+1)
    return {2,*compress(range(3,n,2), sieve[1:])}


list_of_primes = prime_number(10**8)

def divisor_generator(num):
    '''Generates the divisiors of input num'''
    gen = []
    number = num
    for i in list_of_primes:
        while num % i == 0:
            if i < num //2:
                gen.append(num // i)
                gen.append(number // (num //i))
                num = num // i
            else:
                break
    return sorted([1, *gen, number])

在这段代码中,我试图创建一种使用质数来生成数字除数的最快方法。我需要测试最多10 ** 8的数字。但是,divisor_generator函数存在一些问题,并且速度太慢。如何提高代码速度

1 个答案:

答案 0 :(得分:0)

您无需预先计算所有素数,只需将所有可能的除数(甚至非素数)从2迭代到sqrt(N),它的速度就

from math import sqrt

a = 1620
temp = a
divisors = []

# The largest possible divisor is equal to sqrt(a)
for i in range(2, int(sqrt(a)) + 1):
    while temp % i == 0:
        temp = temp // i
        divisors.append(i)
        print(i)
    if temp == 1:
        break
print(divisors)
  

[2, 2, 3, 3, 3, 3, 5]