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.
- Print the nearest prime number formed by adding prime numbers to N
- Nearest element with at-least one common prime factor
- Round the given number to nearest multiple of 10
- Round the given number to nearest multiple of 10 | Set-2
- Nearest greater number by interchanging the digits
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Find coordinates of a prime number in a Prime Spiral
- Check if a prime number can be expressed as sum of two Prime Numbers
- Number which has the maximum number of distinct prime factors in the range M to N
- Represent a number as a sum of maximum possible number of Prime Numbers
- Check if a number is divisible by all prime divisors of another number
- Largest number less than N whose each digit is prime number
- Number with maximum number of prime factors
- Find third number such that sum of all three number becomes prime