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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem