You are given a number n ( 3 <= n < 10^6 ) and you have to find nearest prime less than n?
Input : n = 10 Output: 7 Input : n = 17 Output: 13 Input : n = 30 Output: 29
A simple solution for this problem is to iterate from n-1 to 2, and for every number, check if it is a prime. If prime, then return it and break the loop. This solution looks fine if there is only one query. But not efficient if there are multiple queries for different values of n.
An efficient solution for this problem is to generate all primes less tha 10^6 using Sieve of Sundaram and store then in a array in increasing order. Now apply modified binary search to search nearest prime less than n. Time complexity of this solution is O(n log n + log n) = O(n log n).
If you have another approach to solve this problem then please share in comments.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print the nearest prime number formed by adding prime numbers to N
- Find Largest Special Prime which is less than or equal to a given number
- Largest number less than N whose each digit is prime number
- Nearest prime number in the array of every array element
- Count pairs with sum as a prime number and less than n
- Sum of largest prime factor of each number less than equal to n
- Print all Prime Quadruplet of a number less than it
- Check if the first and last digit of number N is prime and their sum is less than K
- Number less than equals to N with maximum product of prime factors
- Largest number with maximum trailing nines which is less than N and greater than N-D
- Largest number less than N with digit sum greater than the digit sum of N
- Nearest element with at-least one common prime factor
- Print all prime numbers less than or equal to N
- Numbers less than N which are product of exactly two distinct prime numbers
- Count all the numbers less than 10^6 whose minimum prime factor is N
- Print all Semi-Prime Numbers less than or equal to N
- Sum of Semi-Prime Numbers less than or equal to N
- First element of every K sets having consecutive elements with exactly K prime factors less than N
- Queries for greater than and not less than
- Highest and Smallest power of K less than and greater than equal to N respectively