Search code examples
sieve-algorithmpari

Linear sieving algorithm


Is there a simple pari/gp program which can sieve numbers of the form k*n+c (where n and c fixed) up to a certain prime p and k is restricted within a certain range (a.k.a. for(k=1,10000,)?

Pseudocode:

n = (some number);
c = (some number);
T=[all k values];
forprime(p=2,100000000, for(i=1,#List if((T[i]*n+c)%p==0, (remove the number T[i] from the list)

In other words, start with a list of integers T Test the first prime in the prime range p, and remove integers k from the list T such that k*n+c is divisible by p. Then test the next prime and so on. Do this until you reached the limit of the sieve return, or print the list of candidates. Thanks for help!


Solution

  • The pseudo code you provide seems to be reasonable. Rather than removing from the list it is probably easier and as efficient to just copy it. Use the function select to keep those elements that should be retained rather than removed.

    Some actual code:

    sieve(n,c,plimit,L)={forprime(p=2, plimit, L=select(t->(t*n+c)%p, L); if(!#L, break)); L}
    sieve(8, 3, 70000, [1..10000])
    

    I have also added a check in the loop to exit the loop if the list becomes empty. In the cases I have tried, this seems to happen.