Answer Q queries. Each query gives a range [L, R]. Print how many primes lie in the range and their sum.
With up to 10^5 queries, testing every number in every range is too slow. Precompute once.
Constraints
- 1 ≤ Q ≤ 10^5
- 1 ≤ L ≤ R ≤ 10^6
Input and output
- Input
- First line: Q. Then Q lines `L R`.
- Output
- Q lines: `count sum`.
Examples
Input 1
3
1 10
10 20
14 16Output
4 17
4 60
0 01–10 has the primes 2, 3, 5 and 7 (sum 17). 10–20 has 11, 13, 17 and 19 (sum 60). 14–16 has none.
Input 2
2
2 2
1 1Output
1 2
0 02 is prime; 1 is not.
Show hints
- The Sieve of Eratosthenes marks every composite up to N in O(N log log N).
- Prefix arrays turn each query into two lookups:
cnt[R] − cnt[L−1]. - The sum of all primes up to 10^6 is larger than 2^31, so use 64-bit integers.
Show the explanation
1. Sieve up to N = max R. Start by assuming everything from 2 upwards is prime. For each i with i * i ≤ N that is still marked prime, mark i*i, i*i + i, … as composite. Start at i*i because smaller multiples were already marked by smaller primes. The total work is O(N log log N).
2. Prefix arrays. cnt[x] = number of primes ≤ x, and sum[x] = sum of primes ≤ x. Each is built in one pass.
3. Each query is cnt[R] − cnt[L−1] and sum[R] − sum[L−1], which is O(1).
The total is O(N log log N + Q), compared with O(Q · range · √R) for trial division, which is hopeless at these limits.
Pitfalls
- 1 is not prime. Mark 0 and 1 before sieving.
- The sum of primes below 10^6 is about 3.7 × 10^10, which overflows a 32-bit
int. Uselong longin C++. In JavaScript aNumberholds integers exactly up to 2^53, which is enough. - Memory: a byte array of size 10^6 is about 1 MB. A bitset makes it 8 times smaller.
Follow-up: for ranges near 10^12 you cannot sieve all the way up. A segmented sieve uses the primes up to √R to sieve only the window [L, R].
Original UniCircle question. Last reviewed 22 Oct 2026.
