Replace all array elements with the nearest power of its previous element | Java program for the above approach ; Function to calculate log x for given base ; Function to replace all array elements with the nearest power of previous adjacent nelement ; For the first element , set the last array element to its previous element ; Traverse the array ; Find K for which x ^ k is nearest to arr [ i ] ; Find the power to x nearest to arr [ i ] ; Update x ; Driver Code ; Function Call ; Display the array
import java . util . * ; class GFG { static int LOG ( int a , int b ) { return ( int ) ( Math . log ( a ) / Math . log ( b ) ) ; } static void repbyNP ( int [ ] arr , int n ) { int x = arr [ n - 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { int k = LOG ( arr [ i ] , x ) ; int temp = arr [ i ] ; if ( Math . abs ( Math . pow ( x , k ) - arr [ i ] ) < Math . abs ( Math . pow ( x , k + 1 ) - arr [ i ] ) ) arr [ i ] = ( int ) Math . pow ( x , k ) ; else arr [ i ] = ( int ) Math . pow ( x , k + 1 ) ; x = temp ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 3 , 11 } ; int n = arr . length ; repbyNP ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }