Count pairs in array such that one element is power of another | C ++ program to count pairs in array such that one element is power of another ; Function to check if given number number y is power of x ; log function to calculate value ; compare to the result1 or result2 both are equal ; Function to find pairs from array ; Iterate through all pairs ; Increment count if one is the power of other ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x , int y ) { int res1 = log ( y ) / log ( x ) ; double res2 = log ( y ) / log ( x ) ; return ( res1 == res2 ) ; } int countPower ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isPower ( arr [ i ] , arr [ j ] ) || isPower ( arr [ j ] , arr [ i ] ) ) res ++ ; return res ; } int main ( ) { int a [ ] = { 16 , 2 , 3 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPower ( a , n ) ; return 0 ; }