Check if N is a Balanced Prime number or not | 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 that returns true if n is a Balanced prime ; If n is not a prime number or n is the first prime then return false ; Initialize previous_prime to n - 1 and next_prime to n + 1 ; Find next prime number ; Find previous prime number ; Arithmetic mean ; If n is a weak prime ; 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 += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isBalancedPrime ( n ) : NEW_LINE INDENT if not isPrime ( n ) or n == 2 : NEW_LINE INDENT return False NEW_LINE DEDENT previous_prime = n - 1 NEW_LINE next_prime = n + 1 NEW_LINE while not isPrime ( next_prime ) : NEW_LINE INDENT next_prime += 1 NEW_LINE DEDENT while not isPrime ( previous_prime ) : NEW_LINE INDENT previous_prime -= 1 NEW_LINE DEDENT mean = ( previous_prime + next_prime ) / 2 NEW_LINE if n == mean : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 53 NEW_LINE if isBalancedPrime ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT