Friday, July 5, 2024
HomeLanguagesPythonPython3 Program to Count Primes in Ranges

Python3 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]. 
 

Python3




# Python3 program to answer queries for 
# count of primes in given range.
MAX = 10000
  
# prefix[i] is going to
# store count of primes
# till i (including i).
prefix =[0]*(MAX + 1)
  
def buildPrefix():
      
    # Create a boolean array value in
    # prime[i] will "prime[0..n]". A 
    # finally be false if i is Not a
    # prime, else true.
    prime = [1]*(MAX + 1)
  
    p = 2
    while(p * p <= MAX): 
  
        # If prime[p] is not changed, 
        # then it is a prime
        if (prime[p] == 1):
  
            # Update all multiples of p
            i = p * 2
            while(i <= MAX):
                prime[i] = 0
                i += p
        p+=1
  
    # Build prefix array
    # prefix[0] = prefix[1] = 0;
    for p in range(2,MAX+1): 
        prefix[p] = prefix[p - 1]
        if (prime[p]==1):
            prefix[p]+=1
  
# Returns count of primes 
# in range from L to
# R (both inclusive).
def query(L, R):
    return prefix[R]-prefix[L - 1]
  
# Driver code
if __name__=='__main__':
    buildPrefix()
  
    L = 5
    R = 10
    print(query(L, R))
  
    L = 1
    R = 10
    print(query(L, R))
  
# This code is contributed by mits.


Output:  

2
4

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.
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000neveropen! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments