Given n queries of the form range [L, R]. The task is to find the maximum difference between two prime numbers in the range for each query. If there are no prime in the range then print 0. All ranges are below 100005.
Input : Q = 3 query1 = [2, 5] query2 = [2, 2] query3 = [24, 28] Output : 3 0 0 In first query, 2 and 5 are prime number in the range with maximum difference which is 3. In second and third queries, there is only 1 prime number in range, so output is 0.
The idea is to compute Prime numbers using Sieve of Eratosthenes along with some precomputing.
Below are the step to solve the question:
Step 1: Find the prime numbers using Sieve of Eratosthenes algorithm.
Step 2: Make an array, let say prefix, where prefix[i] represents largest prime number smaller or equal to i.
Step 3: Make an array, let say suffix, where suffix[i] represents smallest prime number greater or equal to i.
Step 4: Now for each query having [L, R], do the following:
if (prefix[R] R) return 0; else return prefix[R] - suffix[L];
Below is the implementation of this approach:
3 0 0
- Queries for the difference between the count of composite and prime numbers in a given range
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Pair of prime numbers with a given sum and minimum absolute difference
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Minimum and Maximum prime numbers in an array
- Maximum no. of contiguous Prime Numbers in an array
- Minimum and Maximum Prime Numbers of a Singly Linked List
- Program to find the maximum difference between the index of any two different numbers
- P - smooth numbers in given ranges
- Choose points from two ranges such that no point lies in both the ranges
- Represent a number as a sum of maximum possible number of Prime Numbers
- Queries on the sum of prime factor counts in a range
- Prime Factorization using Sieve O(log n) for multiple queries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.