Find the absolute difference between the nearest powers of two given integers for every array element | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void nearestPowerDiff ( int arr [ ] , int N , int a , int b ) { for ( int i = 0 ; i < N ; i ++ ) { int log_a = log ( arr [ i ] ) / log ( a ) ; int A = pow ( a , log_a ) ; int B = pow ( a , log_a + 1 ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_a = A ; else log_a = B ; int log_b = log ( arr [ i ] ) / log ( b ) ; A = pow ( b , log_b ) ; B = pow ( b , log_b + 1 ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_b = A ; else log_b = B ; arr [ i ] = abs ( log_a - log_b ) ; } printArray ( arr , N ) ; } int main ( ) { int arr [ ] = { 5 , 12 , 25 } ; int A = 2 , B = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPowerDiff ( arr , N , A , B ) ; return 0 ; }