Sieve of Eratosthenes
Learn about sieve of Eratosthenes
Introduction
We are given the range of numbers , and we need to find all prime numbers in this range.
For example, in the range
the prime numbers are:
Learn about sieve of Eratosthenes
We are given the range of numbers , and we need to find all prime numbers in this range.
For example, in the range
the prime numbers are:
The classical algorithm for this task is the Sieve of Eratosthenes.
While processing numbers in the range, we can immediately mark all multiples of the current prime number as composite.
For example:
2, we can mark all multiples of 2 as composite;3, we can mark all multiples of 3 as composite;This allows us to gradually remove all non-prime numbers.

Recall an important fact: if a number is composite, then it has a prime divisor not greater than .
Therefore, to find all primes up to , it is enough to perform the sieving process only with numbers up to .
We create an array prime, where:
prime[x] = true means that x is currently considered prime;prime[x] = false means that x is composite.Initially, all numbers are marked as prime except 0 and 1.
Then for each number i from 2 to :
i is still marked as prime, then mark all multiples of i as composite.The inner loop starts from , because all smaller multiples of have already been processed earlier.
For example, if we are at i = 5, then:
10 = 2 \cdot 5 has already been marked when processing 2;15 = 3 \cdot 5 has already been marked when processing 3;20 = 4 \cdot 5 has already been marked even earlier.So the first new multiple we need to mark is .
In some problems, the value may overflow the int type.
In such cases, it is safer to cast i to long long before multiplication.
For example:
int n;
vector<bool> prime(n + 1, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= n; ++i) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; 1LL * i * i <= n; ++i) {
...
}