Find the absolute difference between the nearest powers of two given integers for every array element | Java 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 java . io . * ; class GFG { static void printArray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void nearestPowerDiff ( int [ ] arr , int N , int a , int b ) { for ( int i = 0 ; i < N ; i ++ ) { int log_a = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( a ) ) ; int A = ( int ) ( Math . pow ( a , log_a ) ) ; int B = ( int ) ( Math . pow ( a , log_a + 1 ) ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_a = A ; else log_a = B ; int log_b = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( b ) ) ; A = ( int ) ( Math . pow ( b , log_b ) ) ; B = ( int ) ( 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 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 12 , 25 } ; int A = 2 , B = 3 ; int N = arr . length ; nearestPowerDiff ( arr , N , A , B ) ; } }