Find the nearest power of 2 for every array element | Python program to implement the above approach ; Function to find the nearest power of two for every array element ; Traverse the array ; Calculate log of current array element ; Find the nearest ; Driver Code
import math NEW_LINE def nearestPowerOfTwo ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT lg = ( int ) ( math . log2 ( arr [ i ] ) ) NEW_LINE a = ( int ) ( math . pow ( 2 , lg ) ) NEW_LINE b = ( int ) ( math . pow ( 2 , lg + 1 ) ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE INDENT print ( a , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( b , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 2 , 7 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE nearestPowerOfTwo ( arr , N ) NEW_LINE