Wednesday, July 9, 2025
HomeData Modelling & AIC++ Program to Count Primes in Ranges

C++ Program to Count Primes in Ranges

Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.
Examples: 
 

Input : Query 1 : L = 1, R = 10
        Query 2 : L = 5, R = 10
Output : 4
         2
Explanation
Primes in the range L = 1 to R = 10 are 
{2, 3, 5, 7}. Therefore for query, answer 
is 4 {2, 3, 5, 7}.
For the second query, answer is 2 {5, 7}.

 

A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.
An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1]. 
 

C++




// CPP program to answer queries for count of
// primes in given range.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 10000;
  
// prefix[i] is going to store count of primes
// till i (including i).
int prefix[MAX + 1];
  
void buildPrefix()
{
    // Create a boolean array "prime[0..n]". A 
    // value in prime[i] will finally be false 
    // if i is Not a prime, else true.
    bool prime[MAX + 1];
    memset(prime, true, sizeof(prime));
  
    for (int p = 2; p * p <= MAX; p++) {
  
        // If prime[p] is not changed, then 
        // it is a prime
        if (prime[p] == true) {
  
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
  
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p])
            prefix[p]++;
    }
}
  
// Returns count of primes in range from L to
// R (both inclusive).
int query(int L, int R)
{
    return prefix[R] - prefix[L - 1];
}
  
// Driver code
int main()
{
    buildPrefix();
  
    int L = 5, R = 10;
    cout << query(L, R) << endl;
  
    L = 1, R = 10;
    cout << query(L, R) << endl;
  
    return 0;
}


Output:  

2
4

Time & Space Complexity will be same as Sieve of eratosthenes

Time Complexity: O(n*log(log(n)))

Auxiliary Space: O(n)

Please refer complete article on Count Primes in Ranges for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32126 POSTS0 COMMENTS
Milvus
66 POSTS0 COMMENTS
Nango Kala
6510 POSTS0 COMMENTS
Nicole Veronica
11658 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11714 POSTS0 COMMENTS
Shaida Kate Naidoo
6605 POSTS0 COMMENTS
Ted Musemwa
6865 POSTS0 COMMENTS
Thapelo Manthata
6565 POSTS0 COMMENTS
Umr Jansen
6558 POSTS0 COMMENTS