Find the absolute difference between the nearest powers of two given integers for every array element | Python3 program for the above approach ; Function to print the array ; Traverse the array ; Function to modify array elements by absolute difference of the nearest perfect power of a and b ; Traverse the array arr [ ] ; Find the log a of arr [ i ] ; Find the power of a less than and greater than a ; Find the log b of arr [ i ] ; Find the power of b less than and greater than b ; Update arr [ i ] with absolute difference of log_a & log _b ; Print the modified array ; Driver Code
import math NEW_LINE def printArray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def nearestPowerDiff ( arr , N , a , b ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT log_a = int ( math . log ( arr [ i ] ) / math . log ( a ) ) NEW_LINE A = int ( pow ( a , log_a ) ) NEW_LINE B = int ( pow ( a , log_a + 1 ) ) NEW_LINE if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) : NEW_LINE INDENT log_a = A NEW_LINE DEDENT else : NEW_LINE INDENT log_a = B NEW_LINE DEDENT log_b = int ( math . log ( arr [ i ] ) / math . log ( b ) ) NEW_LINE A = int ( pow ( b , log_b ) ) NEW_LINE B = int ( pow ( b , log_b + 1 ) ) NEW_LINE if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) : NEW_LINE INDENT log_b = A NEW_LINE DEDENT else : NEW_LINE INDENT log_b = B NEW_LINE DEDENT arr [ i ] = abs ( log_a - log_b ) NEW_LINE DEDENT printArray ( arr , N ) NEW_LINE DEDENT arr = [ 5 , 12 , 25 ] NEW_LINE A = 2 NEW_LINE B = 3 NEW_LINE N = len ( arr ) NEW_LINE nearestPowerDiff ( arr , N , A , B ) NEW_LINE