For several numbers n, count how many prime numbers are at most n.
What to build
Run the sieve of Eratosthenes once up to the largest n, then count the primes up to each n with a prefix count, so every query is O(1).
Requirements
- Run the sieve once, not once per query
- Answer each query in O(1) with a prefix count
Input
The first line has q. Each of the next q lines has a number n.
Output
For each n, the number of primes at most n, one per line.
Constraints
1 ≤ q ≤ 2,000. 1 ≤ n ≤ 20,000.
Example
Input:
4
1
2
10
30
Output:
0
1
4
10
Why it works
The sieve marks all composites up to 20000 in O(n log log n). A running count of unmarked numbers from 2 upwards stores in pi[i] how many primes are at most i, so each query is a lookup.
Examples
4 1 2 10 30
0 1 4 10
2 100 20000
25 2262
Hints
Hint 1
vector<bool> composite(20001, false); mark multiples starting at p * p for each unmarked p.
Hint 2
pi[i] = pi[i - 1] + (i >= 2 && !composite[i] ? 1 : 0).
Hint 3
Then print pi[n] for each query.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int N = 20000;
vector<bool> composite(N + 1, false);
for (int p = 2; p * p <= N; p++)
if (!composite[p])
for (int m = p * p; m <= N; m += p) composite[m] = true;
vector<int> pi(N + 1, 0);
for (int i = 2; i <= N; i++) pi[i] = pi[i - 1] + (composite[i] ? 0 : 1);
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
cout << pi[n] << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step