Given an array arr[], the task is to count the pairs in the array such that one element is the power of another in each pair.
Examples:
Input: arr[] = {16, 2, 3, 9}
Output: 2
The 2 pairs are (16, 2) and (3, 9)
Input: arr[] = {2, 3, 5, 7}
Output: 0
Approach:
- After taking the array as input, first we need to find out all the possible pairs in that array.
- So, find out the pairs from the array
- Then for each pair, check whether an element is a power of another. If it is, then increase the required count by one.
- When all the pairs have been checked, return or print the count of such pair.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
class GFG
{
static boolean isPower( int x, int y)
{
int res1 = ( int )(Math.log(y) / Math.log(x));
double res2 = Math.log(y) / Math.log(x);
return (res1 == res2);
}
static 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;
}
public static void main (String[] args)
{
int a[] = { 16 , 2 , 3 , 9 };
int n =a.length;
System.out.println(countPower(a, n));
}
}
|
Python3
from math import log
def isPower(x, y) :
res1 = log(y) / / log(x);
res2 = log(y) / log(x);
return (res1 = = res2);
def countPower( arr, n) :
res = 0 ;
for i in range (n) :
for j in range (i + 1 , n) :
if isPower(arr[i], arr[j]) or isPower(arr[j], arr[i]) :
res + = 1 ;
return res;
if __name__ = = "__main__" :
a = [ 16 , 2 , 3 , 9 ];
n = len (a);
print (countPower(a, n));
|
C#
using System;
public class GFG
{
static bool isPower( int x, int y)
{
int res1 = ( int )(Math.Log(y) / Math.Log(x));
double res2 = Math.Log(y) / Math.Log(x);
return (res1 == res2);
}
static 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;
}
public static void Main ()
{
int []a = { 16, 2, 3, 9 };
int n =a.Length;
Console.WriteLine(countPower(a, n));
}
}
|
Javascript
<script>
function isPower(x, y)
{
var res1 = parseInt(Math.log(y) / Math.log(x));
var res2 = Math.log(y) / Math.log(x);
return (res1 == res2);
}
function countPower(arr, n)
{
var res = 0;
for ( var i = 0; i < n; i++)
for ( var j = i + 1; j < n; j++)
if (isPower(arr[i], arr[j])
|| isPower(arr[j], arr[i]))
res++;
return res+1;
}
var a = [ 16, 2, 3, 9 ];
var n = a.length;
document.write(countPower(a, n));
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(1)