Related Articles

Related Articles

Java Program For Closest Prime Number
  • Difficulty Level : Medium
  • Last Updated : 02 Nov, 2020

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

Examples:

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).

Approach : 

  1. Using Sieve of Eratosthenes store all prime numbers in a Vector.
  2. Copy all elements in vector to the new array.
  3. Use the upper bound to find the upper bound of the given number in an array.
  4. As the array is already sorted in nature, compare previous and current indexed numbers in an array.
  5. Return number with the smallest difference.

Below is the implementation of the approach.



Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Closest Prime Number in Java
  
import java.util.*;
import java.lang.*;
  
public class GFG {
  
    static int max = 100005;
  
    static Vector<Integer> primeNumber = new Vector<>();
  
    static void sieveOfEratosthenes()
    {
  
        // Create a boolean array "prime[0..n]" and
        // initialize all entries it as true. A value
        // in prime[i] will finally be false if i is
        // Not a prime, else true.
        boolean prime[] = new boolean[max + 1];
        for (int i = 0; i <= max; i++)
            prime[i] = true;
  
        for (int p = 2; p * p <= max; p++) {
  
            // If prime[p] is not changed, then it is a
            // prime
            if (prime[p] == true) {
  
                // Update all multiples of p
                for (int i = p * p; i <= max; i += p)
                    prime[i] = false;
            }
        }
  
        // Print all prime numbers
        for (int i = 2; i <= max; i++) {
  
            if (prime[i] == true)
                primeNumber.add(i);
        }
    }
  
    static int upper_bound(Integer arr[], int low, int high,
                           int X)
    {
        // Base Case
        if (low > high)
            return low;
  
        // Find the middle index
        int mid = low + (high - low) / 2;
  
        // If arr[mid] is less than
        // or equal to X search in
        // right subarray
        if (arr[mid] <= X) {
            return upper_bound(arr, mid + 1, high, X);
        }
  
        // If arr[mid] is greater than X
        // then search in left subarray
        return upper_bound(arr, low, mid - 1, X);
    }
  
    public static int closetPrime(int number)
    {
  
        // We will handle it (for number = 1) explicitly
        // as the lower/left number of 1 can give us
        // negative index which will cost Runtime Error.
        if (number == 1)
            return 2;
        else {
  
            // calling seive of eratosthenes to
            // fill the array into prime numbers
            sieveOfEratosthenes();
  
            Integer[] arr = primeNumber.toArray(
                new Integer[primeNumber.size()]);
            // searching the index
            int index
                = upper_bound(arr, 0, arr.length, number);
  
            if (arr[index] == number
                || arr[index - 1] == number)
                return number;
            else if (Math.abs(arr[index] - number)
                     < Math.abs(arr[index - 1] - number))
                return arr[index];
            else
                return arr[index - 1];
        }
    }
    // Driver Program
    public static void main(String[] args)
    {
        int number = 100;
        System.out.println(closetPrime(number));
    }
}

chevron_right


Output

101






Time Complexity: O(N log(log(N)))

Space Complexity: O(N)

 

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :