Count pairs in Array whose product is a Kth power of any positive integer
Given an array arr[] of length N and an integer K, the task is to count pairs in the array whose product is Kth power of a positive integer, i.e.
A[i] * A[j] = ZK for any positive integer Z.
Examples:
Input: arr[] = {1, 3, 9, 8, 24, 1}, K = 3
Output: 5
Explanation: There are 5 such pairs, those can be represented as Z3 – A[0] * A[3] = 1 * 8 = 2^3 A[0] * A[5] = 1 * 1 = 1^3 A[1] * A[2] = 3 * 9 = 3^3 A[2] * A[4] = 9 * 24 = 6^3 A[3] * A[5] = 8 * 1 = 2^3
Input: arr[] = {7, 4, 10, 9, 2, 8, 8, 7, 3, 7}, K = 2
Output: 7
Explanation: There are 7 such pairs, those can be represented as Z2
Approach: The key observation in this problem is for representing any number in the form of ZK then powers of prime factorization of that number must be multiple of K. Below is the illustration of the steps:
- Compute the prime factorization of each number of the array and store the prime factors in the form of key-value pair in a hash-map, where the key will be a prime factor of that element and value will be the power raised to that prime factor modulus K, in the prime factorization of that number.
For Example:
Given Element be - 360 and K = 2 Prime Factorization = 23 * 32 * 51 Key-value pairs for this would be, => {(2, 3 % 2), (3, 2 % 2), (5, 1 % 2)} => {(2, 1), (5, 1)} // Notice that prime number 3 // is ignored because of the // modulus value was 0
- Traverse over the array and create a frequency hash-map in which the key-value pairs would be defined as follows:
Key: Prime Factors pairs mod K Value: Frequency of this Key
- Finally, Traverse for each element of the array and check required prime factors are present in hash-map or not. If yes, then there will be F number of possible pairs, where F is the frequency.
Example:
Given Number be - 360, K = 3 Prime Factorization - => {(3, 2), (5, 1)} Required Prime Factors - => {(p1, K - val1), ...(pn, K - valn)} => {(3, 3 - 2), (5, 3 - 1)} => {(3, 1), (5, 2)}
Below is the implementation of the above approach:
C++
// C++ implementation to count the // pairs whose product is Kth // power of some integer Z #include <bits/stdc++.h> #define MAXN 100005 using namespace std; // Smallest prime factor int spf[MAXN]; // Sieve of eratosthenes // for computing primes void sieve() { int i, j; spf[1] = 1; for (i = 2; i < MAXN; i++) spf[i] = i; // Loop for markig the factors // of prime number as non-prime for (i = 2; i < MAXN; i++) { if (spf[i] == i) { for (j = i * 2; j < MAXN; j += i) { if (spf[j] == j) spf[j] = i; } } } } // Function to factorize the // number N into its prime factors vector<pair< int , int > > getFact( int x) { // Prime factors along with powers vector<pair< int , int > > factors; // Loop while the X is not // equal to 1 while (x != 1) { // Smallest prime // factor of x int z = spf[x]; int cnt = 0; // Count power of this // prime factor in x while (x % z == 0) cnt++, x /= z; factors.push_back( make_pair(z, cnt)); } return factors; } // Function to count the pairs int pairsWithKth( int a[], int n, int k) { // Precomputation // for factorisation sieve(); int answer = 0; // Data structure for storing // list L for each element along // with frequency of occurrence map<vector<pair< int , int > >, int > count_of_L; // Loop to iterate over the // elements of the array for ( int i = 0; i < n; i++) { // Factorise each element vector<pair< int , int > > factors = getFact(a[i]); sort(factors.begin(), factors.end()); vector<pair< int , int > > L; // Loop to iterate over the // factors of the element for ( auto it : factors) { if (it.second % k == 0) continue ; L.push_back( make_pair( it.first, it.second % k)); } vector<pair< int , int > > Lx; // Loop to find the required prime // factors for each element of array for ( auto it : L) { // Represents how much remainder // power needs to be added to // this primes power so as to make // it a multiple of k Lx.push_back( make_pair( it.first, (k - it.second + k) % k)); } // Add occurrences of // Lx till now to answer answer += count_of_L[Lx]; // Increment the counter for L count_of_L[L]++; } return answer; } // Driver Code int main() { int n = 6; int a[n] = { 1, 3, 9, 8, 24, 1 }; int k = 3; cout << pairsWithKth(a, n, k); return 0; } |
Python3
# JavaScript implementation to count the # pairs whose product is Kth # power of some integer Z MAXN = 100005 # Smallest prime factor spf = [ None for _ in range (MAXN)]; # Sieve of eratosthenes # for computing primes def sieve(): spf[ 1 ] = 1 ; for i in range ( 2 , MAXN): spf[i] = i; # Loop for markig the factors # of prime number as non-prime for i in range ( 2 , MAXN): if (spf[i] = = i) : for j in range ( 2 * i, MAXN, i): if (spf[j] = = j): spf[j] = i; # Function to factorize the # number N into its prime factors def getFact(x): # Prime factors along with powers factors = []; # Loop while the X is not # equal to 1 while (x ! = 1 ) : # Smallest prime # factor of x z = spf[x]; cnt = 0 ; # Count power of this # prime factor in x while (x % z = = 0 ): cnt + = 1 ; x = int (x / z); factors.append([z, cnt]); return factors; # Function to count the pairs def pairsWithKth(a, n, k): # Precomputation # for factorisation sieve(); answer = 0 ; # Data structure for storing # list L for each element along # with frequency of occurrence count_of_L = dict () # Loop to iterate over the # elements of the array for i in range (n): # Factorise each element factors = getFact(a[i]); factors.sort() L = []; # Loop to iterate over the # factors of the element for it in factors: if (it[ 1 ] % k = = 0 ): continue ; L.append((it[ 0 ], it[ 1 ] % k)) Lx = []; # Loop to find the required prime # factors for each element of array for it in L: # Represents how much remainder # power needs to be added to # this primes power so as to make # it a multiple of k Lx.append((it[ 0 ], (k - it[ 1 ] + k) % k)) Lx = tuple (Lx) L = tuple (L) # Add occurrences of # Lx till now to answer if Lx not in count_of_L: count_of_L[Lx] = 0 ; answer + = count_of_L[Lx]; # Increment the counter for L if L not in count_of_L: count_of_L[L] = 0 ; count_of_L[L] + = 1 ; return answer; # Driver Code n = 6 ; a = [ 1 , 3 , 9 , 8 , 24 , 1 ]; k = 3 ; print (pairsWithKth(a, n, k)) # This code is contributed by phasing17 |
C#
// C# implementation to count the // pairs whose product is Kth // power of some integer Z using System; using System.Linq; using System.Collections; using System.Collections.Generic; // Overriding Equals and GetHashCode sealed class ListComparer : EqualityComparer<List< int []> > { public override bool Equals(List< int []> x, List< int []> y) { if (x.Count != y.Count) return false ; for ( int i = 0; i < x.Count; i++) { if ((x[i][0] != y[i][0]) || (x[i][1] != y[i][1])) return false ; } return true ; } public override int GetHashCode(List< int []> x) { int hc = x.Count; foreach ( int [] val in x) { hc = unchecked (hc * 314159 + (val[0] + val[1])); } return hc; } } class GFG { static int MAXN = 100005; // Smallest prime factor static List< int > spf = new List< int >(); // Sieve of eratosthenes // for computing primes static void sieve() { int i, j; spf.Clear(); spf.Add(0); for (i = 1; i <= MAXN; i++) spf.Add(i); // Loop for markig the factors // of prime number as non-prime for (i = 2; i < MAXN; i++) { if (spf[i] == i) { for (j = i * 2; j < MAXN; j += i) { if (spf[j] == j) spf[j] = i; } } } } // Function to factorize the // number N into its prime factors static List< int []> getFact( int x) { // Prime factors along with powers List< int []> factors = new List< int []>(); // Loop while the X is not // equal to 1 while (x != 1) { // Smallest prime // factor of x int z = spf[x]; int cnt = 0; // Count power of this // prime factor in x while (x % z == 0) { cnt++; x = ( int )(x / z); } factors.Add( new [] { z, cnt }); } return factors; } // Function to count the pairs static int pairsWithKth( int [] a, int n, int k) { // Precomputation // for factorisation sieve(); int answer = 0; // Data structure for storing // list L for each element along // with frequency of occurrence Dictionary<List< int []>, int > count_of_L = new Dictionary<List< int []>, int >( new ListComparer()); // Loop to iterate over the // elements of the array for ( var i = 0; i < n; i++) { // Factorise each element var factors = getFact(a[i]); factors = factors.OrderBy(a1 => a1[0]) .ThenBy(a1 => a1[1]) .ToList(); List< int []> L = new List< int []>(); // Loop to iterate over the // factors of the element foreach ( var it in factors) { if (it[1] % k == 0) continue ; L.Add( new [] { it[0], it[1] % k }); } List< int []> Lx = new List< int []>(); // Loop to find the required prime // factors for each element of array foreach ( var it in L) { // Represents how much remainder // power needs to be added to // this primes power so as to make // it a multiple of k Lx.Add( new [] { it[0], (k - it[1] + k) % k }); } // Add occurrences of // Lx till now to answer if (!count_of_L.ContainsKey(Lx)) count_of_L[Lx] = 0; else answer += count_of_L[Lx]; // Increment the counter for L if (!count_of_L.ContainsKey(L)) count_of_L[L] = 1; else count_of_L[L]++; } return answer; } // Driver Code public static void Main( string [] args) { int n = 6; int [] a = { 1, 3, 9, 8, 24, 1 }; int k = 3; Console.WriteLine(pairsWithKth(a, n, k)); } } // This code is contributed by phasing17 |
Javascript
// JavaScript implementation to count the // pairs whose product is Kth // power of some integer Z let MAXN = 100005 // Smallest prime factor let spf = new Array(MAXN); // Sieve of eratosthenes // for computing primes function sieve() { let i, j; spf[1] = 1; for (i = 2; i < MAXN; i++) spf[i] = i; // Loop for markig the factors // of prime number as non-prime for (i = 2; i < MAXN; i++) { if (spf[i] == i) { for (j = i * 2; j < MAXN; j += i) { if (spf[j] == j) spf[j] = i; } } } } // Function to factorize the // number N into its prime factors function getFact(x) { // Prime factors along with powers let factors = []; // Loop while the X is not // equal to 1 while (x != 1) { // Smallest prime // factor of x let z = spf[x]; let cnt = 0; // Count power of this // prime factor in x while (x % z == 0) { cnt++; x = Math.floor(x / z); } factors.push([z, cnt]); } return factors; } // Function to count the pairs function pairsWithKth(a, n, k) { // Precomputation // for factorisation sieve(); let answer = 0; // Data structure for storing // list L for each element along // with frequency of occurrence let count_of_L = {} // Loop to iterate over the // elements of the array for ( var i = 0; i < n; i++) { // Factorise each element let factors = getFact(a[i]); factors.sort( function (a, b) { if (a[0] == b[0]) return a[1] > b[1]; return a[0] > b[0]; }); let L = []; // Loop to iterate over the // factors of the element for (let it of factors) { if (it[1] % k == 0) continue ; L.push([it[0], it[1] % k]) } let Lx = []; // Loop to find the required prime // factors for each element of array for (let it of L) { // Represents how much remainder // power needs to be added to // this primes power so as to make // it a multiple of k Lx.push([it[0], (k - it[1] + k) % k]) } // Add occurrences of // Lx till now to answer if (!count_of_L.hasOwnProperty(Lx)) count_of_L[Lx] = 0; answer += count_of_L[Lx]; // Increment the counter for L if (!count_of_L.hasOwnProperty(L)) count_of_L[L] = 0; count_of_L[L]++; } return answer; } // Driver Code let n = 6; let a = [ 1, 3, 9, 8, 24, 1 ]; let k = 3; console.log(pairsWithKth(a, n, k)) // This code is contributed by phasing17 |
Java
// Java implementation to count the // pairs whose product is Kth // power of some integer Z import java.util.*; class Main { static int MAXN = 100005 ; // Smallest prime factor static Integer[] spf = new Integer[MAXN]; // Sieve of eratosthenes // for computing primes public static void sieve() { spf[ 1 ] = 1 ; // Loop for markig the factors // of prime number as non-prime for ( int i = 2 ; i < MAXN; i++) { spf[i] = i; } for ( int i = 2 ; i < MAXN; i++) { if (spf[i] == i) { for ( int j = 2 * i; j < MAXN; j += i) { if (spf[j] == j) { spf[j] = i; } } } } } // Function to factorize the // number N into its prime factors public static List<List<Integer>> getFact( int x) { // Prime factors along with powers List<List<Integer>> factors = new ArrayList<>(); // Loop while the X is not // equal to 1 while (x != 1 ) { // Smallest prime // factor of x int z = spf[x]; int cnt = 0 ; // Count power of this // prime factor in x while (x % z == 0 ) { cnt++; x /= z; } List<Integer> factor = new ArrayList<>(); factor.add(z); factor.add(cnt); factors.add(factor); } return factors; } // Function to count the pairs public static int pairsWithKth( int [] a, int n, int k) { // Precomputation // for factorisation sieve(); int answer = 0 ; // Data structure for storing // list L for each element along // with frequency of occurrence Map<List<List<Integer>>, Integer> count_of_L = new HashMap<>(); // Loop to iterate over the // elements of the array for ( int i = 0 ; i < n; i++) { // Factorise each element List<List<Integer>> factors = getFact(a[i]); factors.sort( new Comparator<List<Integer>>() { @Override public int compare(List<Integer> a, List<Integer> b) { return a.get( 0 ).compareTo(b.get( 0 )); } }); List<List<Integer>> L = new ArrayList<>(); // Loop to iterate over the // factors of the element for (List<Integer> it : factors) { if (it.get( 1 ) % k == 0 ) { continue ; } List<Integer> factor = new ArrayList<>(); factor.add(it.get( 0 )); factor.add(it.get( 1 ) % k); L.add(factor); } // Loop to find the required prime // factors for each element of array List<List<Integer>> Lx = new ArrayList<>(); for (List<Integer> it : L) { // Represents how much remainder // power needs to be added to // this primes power so as to make // it a multiple of k List<Integer> factor = new ArrayList<>(); factor.add(it.get( 0 )); factor.add((k - it.get( 1 ) + k) % k); Lx.add(factor); } // Add occurrences of // Lx till now to answer if (!count_of_L.containsKey(Lx)) { count_of_L.put(Lx, 0 ); } answer += count_of_L.get(Lx); // Increment the counter for L if (!count_of_L.containsKey(L)) { count_of_L.put(L, 0 ); } count_of_L.put(L, count_of_L.get(L) + 1 ); } return answer; } // Driver Code public static void main(String[] args) { int n = 6 ; int [] a = { 1 , 3 , 9 , 8 , 24 , 1 }; int k = 3 ; System.out.println(pairsWithKth(a, n, k)); } } // This code is contributed by shiv1o43g |
5
Time complexity: O(N * loglogN)
Auxiliary Space: O(MAXN)
Contact Us