用对数筛选光滑数的索引超出范围错误

2024-09-28 22:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我一直在尝试实现二次筛,并完成了步骤1(在代码中):

f = 44
b = ceil(sqrt(n))
factorBase = [i for i in genPrimes(f) if jacobi(n, i) == 1]
t = [modInverse(n, p) for p in factorBase]
sol1 = [(t[i] - b) % factorBase[i] for i in range(len(t))]
sol2 = [(-t[i] - b) % factorBase[i] for i in range(len(t))]
l = [ln(p) for p in factorBase]
size = 60

这里genPrimes()是Eratosthenes的筛,jacobi检查n是否是二次剩余mod i,modInverse是Tonelli-Shanks算法

二次筛的下一步是:

Initialize a sieve array to 0's. For each odd prime p in the factor
base, add l[p] to the locations sol1[p] + ip and soln[p] + ip of the sieve array, for
i = 0, 1, 2,... For the prime p = 2, sieve only with sol1.

或者如本文所述:

Then I have to add values from 𝑙𝑝 to sieving array to positions 𝑠𝑜𝑙1[𝑗]+𝑖∗factor_base[j] and 
𝑠𝑜𝑙1[𝑗]+𝑖∗ factor_base[j], where 0≤𝑖≤ size and 0≤𝑗≤|factor_base|. And for prime 𝑝=2 add 𝑙𝑝 only to 
positions with sol1.

现在说这些是我的清单:

sieveArray = [0 for i in range(60)]
factorBase = [2,3,7,17,23,29,37,41]
sol1  = [0,0,2,13,11,26,10,28]
sol2 = [0,1,5,14,8,10,17,26]
l = [0.69,1.1,1.95,2.83,3.14,3.37,3.61,3.71] # logs of factorbase rounded to 2 decimals

按照上面所说的,我应该得到这个新的列表:

sieveArray = [1.79,1.1,2.64,1.1,1.79,1.95,1.79,1.1,3.83,3.05,8.77,3.14,3.74,3.93,3.52,1.1,3.74,3.61,1.79,3.0
5,0.69,1.1,1.79,1.95,1.79,1.1,9.72,1.1,5.5,0.0,6.57,7.07,0.69,3.05,4.93,0.0,1.79,3.05,0.69,4.47
,3.74,0.0,1.79,1.1,2.64,1.1,1.79,8.39,4.62,1.1,0.69,3.05,1.79,0.0,10.49,4.47,0.69,4.24,3.74,0.0]

然而,每当我尝试编程时,我都会陷入可怕的混乱,索引超出范围的错误。以下是我的失败代码:

for j in factorBase:
    if j != 2:
        for i in range(0, size):
            try: 
                sieveArray[sol1[j] + (i * factorBase[j])] += l[j]
                sieveArray[sol2[j] + (i * factorBase[j])] += l[j]
            except:
                continue
#Didn't implement case for 2 since I didn't know what I was doing.

请有人向我解释一下我做错了什么,以及我怎样才能得到预期的结果。此外,如果您想了解该步骤的实际说明,请转到第6页(qs算法)第2步或第2步。 没有try-except语句时出错:

sieveArray[sol1[j] + (i * factorBase[j])] += j
    IndexError: list index out of range

注意:没有索引超出范围的错误,因为try除外,但是代码仍然不能正常工作


Tags: theto代码inforbasesizerange