Minimum absolute difference of 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
< ? php function isPrime ( $ N ) { for ( $ i = 2 ; $ i <= sqrt ( $ N ) ; $ i ++ ) { if ( $ N % $ i == 0 ) return false ; } return true ; } function getDifference ( $ N ) { if ( $ N == 0 ) return 2 ; else if ( $ N == 1 ) return 1 ; else if ( isPrime ( $ N ) ) return 0 ; $ aboveN = -1 ; $ belowN = -1 ; $ 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 -- ; } $ diff1 = $ aboveN - $ N ; $ diff2 = $ N - $ belowN ; return min ( $ diff1 , $ diff2 ) ; } $ N = 25 ; echo getDifference ( $ N ) . " STRNEWLINE " ;