BlackFridaySale

Join the waitlist for an extra exclusive deal

Extra savings end in
01Days
00Hrs
39Mins
01Secs
Limited spots only

Count Primes in Range L to R

117
0

You are given a 2D array queries with n rows. Each row contains two integers, L and R. For each query, count the prime numbers from L to R, including both endpoints.

Return the counts in the same order as the queries.

Example 1

Input: queries = [[2, 5], [4, 7]]
Output: [3, 2]
Explanation: The primes in [2, 5] are 2, 3, and 5. The primes in [4, 7] are 5 and 7.

Example 2

Input: queries = [[1, 7], [3, 7]]
Output: [4, 3]
Explanation: The first range contains 2, 3, 5, and 7. The second starts at 3, so it contains 3, 5, and 7.

Brute Force Approach

For each query [L, R], check every number in the range and count how many are prime. For example, in [2, 5], we check 2, 3, 4, and 5. The numbers 2, 3, and 5 are prime, so the count is 3.

A prime number is at least 2 and has no divisors other than 1 and itself. To test a number, try dividing it by each integer from 2 through its square root. If any division has a remainder of 0, the number is composite.

Checking up to the square root is enough because factors come in pairs. If one factor is larger than the square root, its paired factor must be smaller. Therefore, every composite number has a divisor within the range we check.

Process each query independently. This repeats some work when ranges overlap. For example, both [2, 5] and [4, 7] check 4 and 5.

Approach

  1. Initialise an empty result list to store the count for each query.

  2. For each query [L, R], set the prime count to 0.

  3. Visit every number from L through R, inclusive. Skip values below 2.

  4. For each remaining number, try divisors from 2 through its square root.

  5. If any divisor divides the number exactly, it is composite. Otherwise, increase the prime count.

  6. Append the count after checking the entire range.

  7. Return the result after processing all queries.

Dry Run

Count Primes in Range L to R Brute force

Count Primes in Range L to R Brute force

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
// Check whether the number has any divisor other than 1 and itself.
bool isPrime(int number) {
if (number < 2) {
return false;
}
// Every composite number has a factor at or below its square root.
// Using division avoids overflow from computing divisor * divisor.
for (int divisor = 2; divisor <= number / divisor; ++divisor) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
public:
// Return one prime count for each inclusive range, in query order.
vector<int> primesInRange(vector<vector<int>>& queries) {
vector<int> result;
result.reserve(queries.size());
for (const auto& query : queries) {
int left = query[0];
int right = query[1];
// Start a fresh count for each range.
int count = 0;
// Skip values below 2. A long long counter can safely step past INT_MAX.
for (long long number = max(2, left); number <= right; ++number) {
// The loop bounds keep number within the int range here.
if (isPrime(number)) {
++count;
}
}
// Append the count so results follow the original query order.
result.push_back(count);
}
return result;
}
};
int main() {
Solution solution;
vector<vector<int>> queries = {{2, 5}, {4, 7}};
// [2, 5] contains 2, 3, and 5. [4, 7] contains 5 and 7.
for (int count : solution.primesInRange(queries)) {
cout << count << '\n';
}
return 0;
}

Complexity Analysis

Let Q be the number of queries and U be the largest right endpoint.

Time Complexity : O((R - L + 1) × √R) for a query with R ≥ 2. If all Q queries cover most of [2, U], the worst-case upper bound is O(Q × U × √U).

Space Complexity : O(1) auxiliary space, excluding the O(Q) result array.

Optimal Approach

When query ranges overlap, checking every number separately repeats the same primality tests. Instead, find all primes up to the largest right endpoint once using the Sieve of Eratosthenes.

Then build a prefix count array called primeCount, where primeCount[x] stores how many primes are less than or equal to x. This lets us answer a range query by subtracting the primes before its left endpoint from the primes up to its right endpoint.

For example, there are four primes up to 7, namely 2, 3, 5, and 7. There are two primes up to 3, namely 2 and 3. Therefore, [4, 7] contains 4 - 2 = 2 primes.

For a query [L, R], subtract the count at L - 1 so that L itself is included when it is prime. Once the prefix counts are ready, each query takes constant time.

Approach

  1. Find the largest right endpoint U. If U < 2, return 0 for every query.

  2. Create an isPrime array up to U. Initially mark all numbers from 2 onward as prime, and mark 0 and 1 as non-prime.

  3. For each prime p with p × p <= U, mark its multiples starting at p × p as composite. Smaller multiples already have a smaller prime factor.

  4. Build primeCount, adding 1 to the previous count whenever the current number is prime.

  5. For each query [L, R], calculate primeCount[R] - primeCount[L - 1] when L > 1.

  6. If L <= 1, use primeCount[R]. If R < 2, the answer is 0.

  7. Append each answer to the result and return it after processing all queries.

Dry Run

Count Primes in Range L to R Optimal

Count Primes in Range L to R Optimal

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Count primes in each inclusive range using a sieve and prefix counts.
vector<int> primesInRange(vector<vector<int>>& queries) {
// Only generate primes up to the largest right endpoint.
int limit = 0;
for (const auto& query : queries) {
limit = max(limit, query[1]);
}
const int queryCount = queries.size();
vector<int> result(queryCount, 0);
// If every range ends below 2, all counts are already zero.
if (limit < 2) {
return result;
}
// Treat numbers from 2 onward as prime candidates.
vector<bool> isPrime(limit + 1, true);
isPrime[0] = false;
isPrime[1] = false;
// Check candidates up to sqrt(limit). Division avoids overflow.
for (int p = 2; p <= limit / p; ++p) {
if (!isPrime[p]) {
continue;
}
// Start at p * p because smaller multiples were already marked.
for (long long multiple = 1LL * p * p;
multiple <= limit; multiple += p) {
isPrime[multiple] = false;
}
}
// Carry forward the previous count and add 1 if number is prime.
vector<int> primeCount(limit + 1, 0);
for (int number = 2; number <= limit; ++number) {
primeCount[number] = primeCount[number - 1] + isPrime[number];
}
// Use the prefix counts to answer each query in constant time.
for (int i = 0; i < queryCount; ++i) {
int left = queries[i][0];
int right = queries[i][1];
if (right < 2) {
continue;
}
// Subtract the primes strictly before left to keep both endpoints inclusive.
int beforeLeft = left > 1 ? primeCount[left - 1] : 0;
result[i] = primeCount[right] - beforeLeft;
}
return result;
}
};
int main() {
Solution solution;
vector<vector<int>> queries = {{1, 7}, {3, 7}};
// [1, 7] contains 4 primes, and [3, 7] contains 3.
for (int count : solution.primesInRange(queries)) {
cout << count << '\n';
}
return 0;
}

Complexity Analysis

Time Complexity : O(U log log U + Q). The sieve takes O(U log log U), building the prefix counts takes O(U), and finding the upper limit and answering the queries together take O(Q). If the largest endpoint is below 2, the solution takes O(Q) time.

Space Complexity : O(U) auxiliary space for the sieve and prefix counts, excluding the O(Q) result array.

Interview follow-up Questions

The answer is 1 if that number is prime and 0 otherwise. For example, [7, 7] returns 1, while [9, 9] returns 0.

Maths

Read Similar Blogs

Comments0