Modify array by replacing elements with the nearest power of its previous or next element | C ++ program for the above approach ; Function to calculate the power of y which is nearest to x ; Base Case ; Stores the logarithmic value of x with base y ; Function to replace each array element by the nearest power of its previous or next element ; Stores the previous and next element ; Traverse the array ; Calculate nearest power for previous and next elements ; Replacing the array values ; Print the updated array ; Driver Code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nearestPow ( int x , int y ) { if ( y == 1 ) return 1 ; int k = log10 ( x ) / log10 ( y ) ; if ( abs ( pow ( y , k ) - x ) < abs ( pow ( y , ( k + 1 ) ) - x ) ) return pow ( y , k ) ; return pow ( y , ( k + 1 ) ) ; } void replacebyNearestPower ( vector < int > arr ) { int prev = arr [ arr . size ( ) - 1 ] ; int lastNext = arr [ 0 ] ; int next = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int temp = arr [ i ] ; if ( i == arr . size ( ) - 1 ) next = lastNext ; else next = arr [ ( i + 1 ) % arr . size ( ) ] ; int prevPow = nearestPow ( arr [ i ] , prev ) ; int nextPow = nearestPow ( arr [ i ] , next ) ; if ( abs ( arr [ i ] - prevPow ) < abs ( arr [ i ] - nextPow ) ) arr [ i ] = prevPow ; else arr [ i ] = nextPow ; prev = temp ; } for ( int i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { vector < int > arr { 2 , 3 , 4 , 1 , 2 } ; replacebyNearestPower ( arr ) ; }