Given an array of integers where all the elements are less than 10^6.
The task is to find the difference between the largest and the smallest prime numbers in the array.
Input : Array = 1, 2, 3, 5 Output : Difference is 3 Explanation : The largest prime number in the array is 5 and the smallest is 2 So, the difference is 3 Input : Array = 3, 5, 11, 17 Output : Difference is 14
A Simple approach:
In the basic approach, we will check every element of the array whether it is prime or not.
Then, select the largest and the smallest prime numbers and print the difference.
The efficient approach is much similar to the basic approach.
We will try to reduce the time for checking the number against prime by creating a Sieve of Eratosthenes to check whether the number is prime or not in O(1) time.
And then, we will select the largest and the smallest prime numbers and print the difference.
Below is the implementation of the above approach:
Difference is 3
- Length of largest sub-array having primes strictly greater than non-primes
- Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..
- K'th Smallest/Largest Element in Unsorted Array | Set 1
- Largest and smallest Fibonacci numbers in an Array
- Sum and product of k smallest and k largest prime numbers in the array
- Sum and product of k smallest and k largest composite numbers in the array
- kth smallest/largest in a small range unsorted array
- Sum and product of K smallest and largest Fibonacci numbers in the array
- k largest(or smallest) elements in an array | added Min Heap method
- K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
- Replace elements with absolute difference of smallest element on left and largest element on right
- K'th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
- k-th smallest absolute difference of two elements in an array
- Average of remaining elements after removing K largest and K smallest elements from array
- Minimum difference between any two primes from the given range
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.