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 firstname.lastname@example.org. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print the nearest prime number formed by adding prime numbers to N
- Nearest prime number in the array of every array element
- Nearest element with at-least one common prime factor
- Round the given number to nearest multiple of 10 | Set-2
- Round the given number to nearest multiple of 10
- Nearest greater number by interchanging the digits
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Check if a prime number can be expressed as sum of two Prime Numbers
- Find coordinates of a prime number in a Prime Spiral
- Number of factors of very large number N modulo M where M is any prime number
- Find the minimum number to be added to N to make it a prime number
- Number which has the maximum number of distinct prime factors in the range M to N
- Count of prime digits of a Number which divides the number
- Check if a number is divisible by all prime divisors of another number
- Represent a number as a sum of maximum possible number of Prime Numbers
- Number with maximum number of prime factors
- Check if the number is a Prime power number
- Largest number less than N whose each digit is prime number
- Find third number such that sum of all three number becomes prime