Count pairs in Array whose product is a Kth power of any positive integer
Last Updated :
15 Mar, 2023
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
Time complexity: O(N * loglogN)
Auxiliary Space: O(MAXN)
Similar Reads
Count of index pairs in array whose range product is a positive integer
Given an array A of non-zero integers, the task is to find the number of pairs (l, r) where (l <= r) such that A[l]*A[l+1]*A[l+2]....A[r] is positive. Examples: Input: A = {5, -3, 3, -1, 1} Output: 7 Explanation: First pair, (1, 1) = 5 is positive Second pair, (3, 3) = 3 is positive Third pair, (
6 min read
Count of integers in an Array whose length is a multiple of K
Given an array arr of N elements and an integer K, the task is to count all the elements whose length is a multiple of K.Examples: Input: arr[]={1, 12, 3444, 544, 9}, K = 2 Output: 2 Explanation: There are 2 numbers whose digit count is multiple of 2 {12, 3444}. Input: arr[]={12, 345, 2, 68, 7896},
5 min read
Count of pairs in Array whose product is divisible by K
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K. Examples : Input: A[] = [1, 2, 3, 4, 5], K = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
9 min read
Count all possible pairs in given Array with product K
Given an integer array arr[] of size N and a positive integer K, the task is to count all the pairs in the array with a product equal to K. Examples: Input: arr[] = {1, 2, 16, 4, 4, 4, 8 }, K=16Output: 5Explanation: Possible pairs are (1, 16), (2, 8), (4, 4), (4, 4), (4, 4) Input: arr[] = {1, 10, 20
11 min read
Count pairs of indices with a specific property in an Array
Given an array a[] of size n containing only non-negative integers, and an integer k, the task is to find the number of pairs of indices (i, j) such that i < j and k * a[i] ⤠a[j]. Examples: Input: a[] = {3, 5, 2, 4}, n = 4, k = 2Output: 6Explanation: The pairs satisfying the condition are: (1, 3
4 min read
Minimum product of k integers in an array of positive Integers
Given an array arr[] containing n positive integers and an integer k. Your task is to find the minimum possible product of k elements of the given array.Examples: Input: arr[] = [198, 76, 544, 123, 154, 675], k = 2Output: 9348Explanation: We will choose two smallest numbers from the given array to g
7 min read
Count pairs in Array whose product is divisible by K
Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j. Examples: Input: vec = {1, 2, 3, 4, 5, 6}, K = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
11 min read
Count pairs in a sorted array whose product is less than k
Given a sorted integer array and number k, the task is to count pairs in an array whose product is less than x. Examples: Input: A = {2, 3, 5, 6}, k = 16 Output: 4 Pairs having product less than 16: (2, 3), (2, 5), (2, 6), (3, 5) Input: A = {2, 3, 4, 6, 9}, k = 20 Output: 6 Pairs having product less
12 min read
Count pairs whose products exist in array
Given an array, count those pair whose product value is present in array. Examples: Input : arr[] = {6, 2, 4, 12, 5, 3}Output : 3 All pairs whose product exist in array (6 , 2) (2, 3) (4, 3) Input : arr[] = {3, 5, 2, 4, 15, 8}Output : 2 A Simple solution is to generate all pairs of given array and c
15+ min read
Count pairs from an array with even product of count of distinct prime factors
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to count pairs (A[i], B[j]) such that the product of their count of distinct prime factors is even. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 5, 6}, N = 3, M = 3Output: 2Explanation: Replacing all array elements
11 min read