我正在寻找一种算法,可以根据已经分解的数字分解数字。换句话说,我正在寻找一种快速算法来将所有数字分解为给定数字,并将它们存储在(我想这是最容易使用的数据结构)列表/元组元组中。我正在寻找一种“最多 n”的算法,因为我需要最多“n”的所有数字,而且我想这比一个一个地检查要快。
对于我正在运行的程序,我希望此算法在合理的时间内(不到一小时)运行 2*10^8。我在 python 中尝试了一种更天真的方法,首先找到“n”之前的所有素数,然后对于每个数字“k”,通过检查每个素数直到被除以它(我们称之为 p),找到它的素因数分解,那么它的因式分解就是 k/p + p 的因式分解。
from math import *
max=1000000 # We will check all numbers up to this number,
lst = [True] * (max - 2) # This is an algorithm I found online that will make the "PRIMES" list all the primes up to "max", very efficent
for i in range(2, int(sqrt(max) + 1)):
if lst[i - 2]:
for j in range(i ** 2, max, i):
lst[j - 2] = False
PRIMES = tuple([m + 2 for m in range(len(lst)) if lst[m]]) # (all primes up to "max")
FACTORS = [(0,),(1,)] #This will be a list of tuples where FACTORS[i] = the prime factors of i
for c in range(2,max): #check all numbers until max
if c in PRIMES:
FACTORS.append((c,)) #If it's a prime just add it in
else: #if it's not a prime...
i=0
while PRIMES[i]<= c: #Run through all primes until you find one that divides it,
if c%PRIMES[i] ==0:
FACTORS.append(FACTORS[c//PRIMES[i]] + (PRIMES[i],)) #If it does, add the prime with the factors of the division
break
i+=1
从测试来看,绝大多数时间都浪费在检查候选人是否为素数之后的 else 部分。这需要的不仅仅是我们的 for max = 200000000
慕工程0101907
函数式编程
红颜莎娜
随时随地看视频慕课网APP
相关分类