Java Program For Closest Prime Number
Given a number N, you have to print its closest prime number. The prime number can be lesser, equal, or greater than the given number.
Condition: 1 ≤ N ≤ 100000
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : 16 Output: 17 Explanation: The two nearer prime number of 16 are 13 and 17. But among these, 17 is the closest(As its distance is only 1(17-16) from the given number). Input : 97 Output : 97 Explanation : The closest prime number in this case is the given number number itself as the distance is 0 (97-97).
- Using Sieve of Eratosthenes store all prime numbers in a Vector.
- Copy all elements in vector to the new array.
- Use the upper bound to find the upper bound of the given number in an array.
- As the array is already sorted in nature, compare previous and current indexed numbers in an array.
- Return number with the smallest difference.
Below is the implementation of the approach.
Time Complexity: O(N log(log(N)))
Space Complexity: O(N)