Interprime | Utility 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 next_prime and prev_prime have the same average ; Driver Code
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isInterprime ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev_prime = n NEW_LINE next_prime = n NEW_LINE while ( isPrime ( prev_prime ) == 0 ) : NEW_LINE INDENT prev_prime = prev_prime - 1 NEW_LINE DEDENT while ( isPrime ( next_prime ) == 0 ) : NEW_LINE INDENT next_prime = next_prime + 1 NEW_LINE DEDENT if ( ( prev_prime + next_prime ) == 2 * n ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 9 NEW_LINE if ( isInterprime ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT