1

In Sieve of Eratosthenes we sieve the range $[1,N]$ by crossing out 1, then crossing out 2 and multiples of 2, then take 3 and then cross out 3 and multiples of 3 and so on... picking the next uncrossed number as the next prime.

Instead of the range $[1,N]$, if we start with a range $[a,b]$ what is the best approach?

We can start with the first even number in the range which means $a$ or $a+1$. But if $a$ is odd, how do we know whether it is prime or composite (without doing a primality test of course, because we are sieving)?

I am guessing we still have to start the sieving from $2$ to collect primes less than $a$ because we need them to sieve the range $[a,b]$ to eliminate multiples of those primes as this MSE question/answer seems to suggest.

Keep in mind that we are ultimately using the range sieving to see if it contains a factor of $N$. So, the modified method could use GCD computation to throw away $a$ after the GCD returns 1. If not, we have a factor of $N$.

Is there any other trick we can use here?

vvg
  • 3,526
  • 2
    One trick is to sieve on $[0,b]$ and then subtract the sieve result on $[0, a]$... – abiessu Dec 06 '22 at 18:30
  • @abiessu: I am not following. Isn't that just the Sieve of Eratosthenes once we have sieved $[0,b]$ because $a < b$? – vvg Dec 06 '22 at 18:34
  • 2
    Yes, such a sieve is perfectly fine but one still needs to start the sieving at $2$ and use primes less than $a$. – Greg Martin Dec 06 '22 at 18:44

1 Answers1

2

To sieve the range $[a,b]$ you need all primes up to $\sqrt b$. To get these start with sieving the range $[1, \sqrt b]$.

After that you can sieve the range $[a,b]$:

for each prime $p_i$ cross out its multiples starting with the least multiple $m$ of $p_i$ that is greater than $a$: $m = a + p_i - 1 - (a + p_i - 1) \operatorname {mod} p_i$.

Alternatively cross out even numbers first and use the odd primes for sieving in $2p_i$ steps.

Eberhard
  • 193
  • The claim in the first sentence is false. The claim is sufficient but not necessary, by here. – Bill Dubuque Mar 20 '24 at 21:55
  • In the general case it is necessary. For instance if $b = p^2$ and $p$ is prime all primes up to $p = \sqrt p$ are needed; for the range [1, 1000] all primes $\le \sqrt {1000} \approx 31.6$ are needed, otherwise $31^2 = 961$ would not be sieved out. – Eberhard Mar 21 '24 at 11:01
  • But of course we can ignore the lone exception $p^2$ as in the linked post. – Bill Dubuque Mar 21 '24 at 11:50