Minimum absolute difference of a number and its closest prime | Python 3 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
from math import sqrt NEW_LINE def isPrime ( N ) : NEW_LINE INDENT k = int ( sqrt ( N ) ) + 1 NEW_LINE for i in range ( 2 , k , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getDifference ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( isPrime ( N ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT aboveN = - 1 NEW_LINE belowN = - 1 NEW_LINE n1 = N + 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPrime ( n1 ) ) : NEW_LINE INDENT aboveN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 += 1 NEW_LINE DEDENT DEDENT n1 = N - 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPrime ( n1 ) ) : NEW_LINE INDENT belowN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 -= 1 NEW_LINE DEDENT DEDENT diff1 = aboveN - N NEW_LINE diff2 = N - belowN NEW_LINE return min ( diff1 , diff2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( getDifference ( N ) ) NEW_LINE DEDENT