Count primes in range L to R

Maths Sieve of Eratosthenes Hard

You are given an 2D array queries of dimension n*2.

The queries[i] represents a range from queries[i][0] to queries[i][1] (include the end points).

Return the count of prime numbers present in between each range in queries array.

Examples:

Input : queries = [ [2, 5], [4, 7] ]

Output : [3, 2]

Explanation : The range 2 to 5 contains three prime numbers 2, 3, 5.

The range 4 to 7 contains two prime numbers 5, 7.

Input : queries = [ [1, 7], [3, 7] ]

Output : [4, 3]

Explanation : The range 1 to 7 contains four prime numbers 2, 3, 5, 7.

The range 3 to 7 contains three prime numbers 3, 5, 7.

Input : queries = [ [1, 10], [10, 20] ]

Constraints

  • 1 <= n <= 105
  • 1 <= queries[i][0] <= queries[i][1] <= 105

Hints

  • A brute-force approach would check each number in the range [L, R] for primality using trial division, resulting in O(n√m) complexity (where m is the largest number in queries). This is inefficient for large R.
  • "A better approach is the Prefix Sum of Primes using the Sieve of Eratosthenes: Precompute all primes up to max(R) using the Sieve of Eratosthenes (O(m log log m)). Build a prefix sum array where prime_count[i] stores the count of primes from 1 to i (O(m))."

Company Tags

Reddit Zomato Salesforce Zynga Target American Express Lyft Docker Walmart Unity Technologies eBay Mastercard JPMorgan Chase Bain & Company Twilio Byju's Optum Freshworks Siemens Healthineers PwC Broadcom Ubisoft Robinhood Texas Instruments Wayfair Google Microsoft Amazon Meta Apple Netflix Adobe