Interprime | Function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the given number is interprime or not ; Smallest Interprime is 4 So the number less than 4 can not be a Interprime ; Calculate first prime number < n ; Calculate first prime number > n ; Check if prev_prime and next_prime have the same average ; Driver Code
function isPrime ( n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( var i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } function isInterprime ( n ) { if ( n < 4 ) return false ; var prev_prime = n ; var next_prime = n ; while ( ! isPrime ( prev_prime ) ) { prev_prime -- ; } while ( ! isPrime ( next_prime ) ) { next_prime ++ ; } if ( ( prev_prime + next_prime ) == 2 * n ) return true ; else return false ; } var n = 9 ; if ( isInterprime ( n ) ) document . write ( " " ) ; else document . write ( " " ) ;