Replace all array elements with the nearest power of its previous element | CPP 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
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int LOG ( int a , int b ) { return log ( a ) / log ( b ) ; } 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 ( abs ( pow ( x , k ) - arr [ i ] ) < abs ( pow ( x , k + 1 ) - arr [ i ] ) ) arr [ i ] = pow ( x , k ) ; else arr [ i ] = pow ( x , k + 1 ) ; x = temp ; } } int main ( ) { int arr [ 5 ] = { 2 , 4 , 6 , 3 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; repbyNP ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }