Minimum absolute difference of a number and its closest prime | Java program to find the minimum absolute difference between a number and its closest prime ; Function to check if a number is prime or not ; Function to find the minimum absolute difference between a number and its closest prime ; Variables to store first prime above and below N ; Finding first prime number greater than N ; Finding first prime number less than N ; Variables to store the differences ; Driver code
class GFG { static boolean isPrime ( int N ) { for ( int i = 2 ; i <= Math . sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) return false ; } return true ; } static int getDifference ( int N ) { if ( N == 0 ) return 2 ; else if ( N == 1 ) return 1 ; else if ( isPrime ( N ) ) return 0 ; int aboveN = - 1 , belowN = - 1 ; int n1 ; n1 = N + 1 ; while ( true ) { if ( isPrime ( n1 ) ) { aboveN = n1 ; break ; } else n1 ++ ; } n1 = N - 1 ; while ( true ) { if ( isPrime ( n1 ) ) { belowN = n1 ; break ; } else n1 -- ; } int diff1 = aboveN - N ; int diff2 = N - belowN ; return Math . min ( diff1 , diff2 ) ; } public static void main ( String args [ ] ) { int N = 25 ; System . out . println ( getDifference ( N ) ) ; } }