Find the absolute difference between the nearest powers of two given integers for every array element | 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
function printArray ( arr , N ) { for ( let i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } function nearestPowerDiff ( arr , N , a , b ) { for ( let i = 0 ; i < N ; i ++ ) { let log_a = Math . floor ( Math . log ( arr [ i ] ) / Math . log ( a ) ) ; let A = Math . floor ( Math . pow ( a , log_a ) ) ; let B = Math . floor ( Math . pow ( a , log_a + 1 ) ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_a = A ; else log_a = B ; let log_b = Math . floor ( Math . log ( arr [ i ] ) / Math . log ( b ) ) ; A = Math . floor ( Math . pow ( b , log_b ) ) ; B = Math . floor ( Math . pow ( b , log_b + 1 ) ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_b = A ; else log_b = B ; arr [ i ] = Math . abs ( log_a - log_b ) ; } printArray ( arr , N ) ; } let arr = [ 5 , 12 , 25 ] ; let A = 2 , B = 3 ; let N = arr . length ; nearestPowerDiff ( arr , N , A , B ) ;