Minimum absolute difference between N and any power of 2 | Python3 implementation of the approach ; Function to return the highest power of 2 less than or equal to n ; Function to return the smallest power of 2 greater than or equal to n ; Function that returns the minimum absolute difference between n and any power of 2 ; Driver code
from math import log NEW_LINE def prevPowerof2 ( n ) : NEW_LINE INDENT p = int ( log ( n ) ) NEW_LINE return pow ( 2 , p ) NEW_LINE DEDENT def nextPowerOf2 ( n ) : NEW_LINE INDENT p = 1 NEW_LINE if ( n and ( n & ( n - 1 ) ) == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT while ( p < n ) : NEW_LINE INDENT p <<= 1 NEW_LINE DEDENT return p NEW_LINE DEDENT def minDiff ( n ) : NEW_LINE INDENT low = prevPowerof2 ( n ) NEW_LINE high = nextPowerOf2 ( n ) NEW_LINE return min ( n - low , high - n ) NEW_LINE DEDENT n = 6 NEW_LINE print ( minDiff ( n ) ) NEW_LINE