Count pairs whose product contains single distinct prime factor
Last Updated :
26 Sep, 2023
Given an array arr[] of size N, the task is to count the number of pairs from the given array whose product contains only a single distinct prime factor.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Pairs having single distinct prime factor in their product is as follows:
arr[0] * arr[1] = (1 * 2) = 2. Therefore, the single distinct prime factor is 2.
arr[0] * arr[2] = (1 * 3) = 3. Therefore, the single distinct prime factor is 3.
arr[0] * arr[3] = (1 * 4) = 22 Therefore, the single distinct prime factor is 2.
arr[1] * arr[3] = (2 * 4) = 8 23 Therefore, the single distinct prime factor is 2.
Therefore, the required output is 4.
Input: arr[] = {2, 4, 6, 8}
Output: 3
Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible pairs of the array and for each pair, check if the product of elements contains only a single distinct prime factor or not. If found to be true, then increment the count. Finally, print the count.
Time Complexity: O(N2 * √X), where X is the maximum possible product of a pair in the given array.
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is to use Hashing. Follow the steps below to solve the problem:
- Initialize a variable, say cntof1 to store count of array elements whose value is 1.
- Create map, say mp to store the count of array elements which contains only a single distinct prime factor.
- Traverse the array and for each array elements, check if the count of distinct prime factors is 1 or not. If found to be true then insert the current element into mp.
- Initialize a variable, say res to store the count of pairs whose product of elements contains only a single distinct prime factor.
- Traverse the map and update the res += cntof1 * (X) + (X *(X- 1)) / 2. Where X stores the count of the array element which contains only a single distinct prime factor i.
- Finally, print the value of res.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
int singlePrimeFactor( int N)
{
unordered_set< int > disPrimeFact;
for ( int i = 2; i * i <= N; ++i) {
while (N % i == 0) {
disPrimeFact.insert(i);
N /= i;
}
}
if (N != 1) {
disPrimeFact.insert(N);
}
if (disPrimeFact.size() == 1) {
return *disPrimeFact.begin();
}
return -1;
}
int cntsingleFactorPair( int arr[], int N)
{
int countOf1 = 0;
unordered_map< int , int > mp;
for ( int i = 0; i < N; i++) {
if (arr[i] == 1) {
countOf1++;
continue ;
}
int factorValue = singlePrimeFactor(arr[i]);
if (factorValue == -1) {
continue ;
}
else {
mp[factorValue]++;
}
}
int res = 0;
for ( auto it : mp) {
int X = it.second;
res += countOf1 * X + (X * (X - 1)) / 2;
}
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << cntsingleFactorPair(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int singlePrimeFactor( int N)
{
HashSet<Integer> disPrimeFact =
new HashSet<>();
for ( int i = 2 ;
i * i <= N; ++i)
{
while (N % i == 0 )
{
disPrimeFact.add(i);
N /= i;
}
}
if (N != 1 )
{
disPrimeFact.add(N);
}
if (disPrimeFact.size() == 1 )
{
for ( int i : disPrimeFact)
return i;
}
return - 1 ;
}
static int cntsingleFactorPair( int arr[],
int N)
{
int countOf1 = 0 ;
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < N; i++)
{
if (arr[i] == 1 )
{
countOf1++;
continue ;
}
int factorValue =
singlePrimeFactor(arr[i]);
if (factorValue == - 1 )
{
continue ;
}
else
{
if (mp.containsKey(factorValue))
mp.put(factorValue,
mp.get(factorValue) + 1 );
else
mp.put(factorValue, 1 );
}
}
int res = 0 ;
for (Map.Entry<Integer,
Integer> it :
mp.entrySet())
{
int X = it.getValue();
res += countOf1 * X +
(X * (X - 1 ) ) / 2 ;
}
return res;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int N = arr.length;
System.out.print(
cntsingleFactorPair(arr, N));
}
}
|
Python3
def singlePrimeFactor(N):
disPrimeFact = {}
for i in range ( 2 , N + 1 ):
if i * i > N:
break
while (N % i = = 0 ):
disPrimeFact[i] = 1
N / / = i
if (N ! = 1 ):
disPrimeFact[N] = 1
if ( len (disPrimeFact) = = 1 ):
return list (disPrimeFact.keys())[ 0 ]
return - 1
def cntsingleFactorPair(arr, N):
countOf1 = 0
mp = {}
for i in range (N):
if (arr[i] = = 1 ):
countOf1 + = 1
continue
factorValue = singlePrimeFactor(arr[i])
if (factorValue = = - 1 ):
continue
else :
mp[factorValue] = mp.get(factorValue, 0 ) + 1
res = 0
for it in mp:
X = mp[it]
res + = countOf1 * X + (X * (X - 1 ) ) / / 2
return res
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 ]
N = len (arr)
print (cntsingleFactorPair(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int singlePrimeFactor( int N)
{
HashSet< int > disPrimeFact =
new HashSet< int >();
for ( int i = 2;
i * i <= N; ++i)
{
while (N % i == 0)
{
disPrimeFact.Add(i);
N /= i;
}
}
if (N != 1)
{
disPrimeFact.Add(N);
}
if (disPrimeFact.Count == 1)
{
foreach ( int i in disPrimeFact)
return i;
}
return -1;
}
static int cntsingleFactorPair( int []arr,
int N)
{
int countOf1 = 0;
Dictionary< int ,
int > mp =
new Dictionary< int ,
int >();
for ( int i = 0; i < N; i++)
{
if (arr[i] == 1)
{
countOf1++;
continue ;
}
int factorValue =
singlePrimeFactor(arr[i]);
if (factorValue == -1)
{
continue ;
}
else
{
if (mp.ContainsKey(factorValue))
mp[factorValue] = mp[factorValue] + 1;
else
mp.Add(factorValue, 1);
}
}
int res = 0;
foreach (KeyValuePair< int ,
int > ele1 in mp)
{
int X = ele1.Value;
res += countOf1 * X +
(X * (X - 1) ) / 2;
}
return res;
}
public static void Main()
{
int []arr = {1, 2, 3, 4};
int N = arr.Length;
Console.WriteLine(
cntsingleFactorPair(arr, N));
}
}
|
Javascript
<script>
function singlePrimeFactor(N)
{
var disPrimeFact = {};
for ( var i = 2; i * i <= N; ++i)
{
while (N % i === 0)
{
disPrimeFact[i] = 1;
N = parseInt(N / i);
}
}
if (N !== 1)
{
disPrimeFact[N] = 1;
}
if (Object.keys(disPrimeFact).length === 1)
{
for (const [key, value] of Object.entries(
disPrimeFact))
{
return key;
}
}
return -1;
}
function cntsingleFactorPair(arr, N)
{
var countOf1 = 0;
var mp = {};
for ( var i = 0; i < N; i++)
{
if (arr[i] === 1)
{
countOf1++;
continue ;
}
var factorValue = singlePrimeFactor(arr[i]);
if (factorValue === -1)
{
continue ;
}
else
{
if (mp.hasOwnProperty(factorValue))
mp[factorValue] = mp[factorValue] + 1;
else
mp[factorValue] = 1;
}
}
var res = 0;
for (const [key, value] of Object.entries(mp))
{
var X = value;
res = parseInt(res + countOf1 * X +
(X * (X - 1)) / 2);
}
return res;
}
var arr = [ 1, 2, 3, 4 ];
var N = arr.length;
document.write(cntsingleFactorPair(arr, N));
</script>
|
Time Complexity: O(N√X), where X is the maximum element of the given array.
Auxiliary Space: O(N)
Using Brute Force:
Approach:
We can use a nested loop to iterate over all possible pairs of elements in the array and check if their product has a single distinct prime factor. We can use a helper function to determine if a number has a single distinct prime factor.
- Define a function has_single_distinct_prime_factor which takes an integer as input and returns a boolean value indicating whether the integer has a single distinct prime factor.
- Inside the function, initialize an empty set to store the prime factors.
- Divide the input integer by 2 as many times as possible and add 2 to the set of prime factors each time.
- Check for odd factors starting from 3 up to the square root of the input integer.
- If a factor is found, divide the input integer by the factor as many times as possible and add the factor to the set of prime factors each time.
- If the input integer is greater than 2, it is a prime factor, so add it to the set of prime factors.
- Return a boolean value indicating whether the set of prime factors contains only one element.
- Define a function count_pairs which takes a list of integers as input and returns the count of pairs whose product contains a single distinct prime factor.
- Initialize a count variable to 0.
- Iterate over all pairs of integers in the list and check whether their product has a single distinct prime factor using the has_single_distinct_prime_factor function.
- If the product has a single distinct prime factor, increment the count variable.
- Return the count variable.
C++
#include <iostream>
#include <unordered_set>
#include <cmath>
#include <vector>
using namespace std;
bool has_single_distinct_prime_factor( int n) {
unordered_set< int > prime_factors;
while (n % 2 == 0) {
prime_factors.insert(2);
n /= 2;
}
for ( int i = 3; i <= sqrt (n); i += 2) {
while (n % i == 0) {
prime_factors.insert(i);
n /= i;
}
}
if (n > 2) {
prime_factors.insert(n);
}
return prime_factors.size() == 1;
}
int count_pairs(vector< int >& arr) {
int n = arr.size();
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (has_single_distinct_prime_factor(arr[i] * arr[j])) {
count++;
}
}
}
return count;
}
int main() {
vector< int > arr1 = {1, 2, 3, 4};
vector< int > arr2 = {2, 4, 6, 8};
cout << count_pairs(arr1) << endl;
cout << count_pairs(arr2) << endl;
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
public class SingleDistinctPrimeFactor {
static boolean hasSingleDistinctPrimeFactor( int n) {
Set<Integer> primeFactors = new HashSet<>();
while (n % 2 == 0 ) {
primeFactors.add( 2 );
n /= 2 ;
}
for ( int i = 3 ; i <= Math.sqrt(n); i += 2 ) {
while (n % i == 0 ) {
primeFactors.add(i);
n /= i;
}
}
if (n > 2 ) {
primeFactors.add(n);
}
return primeFactors.size() == 1 ;
}
static int countPairs(Vector<Integer> arr) {
int n = arr.size();
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (hasSingleDistinctPrimeFactor(arr.get(i) * arr.get(j))) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Vector<Integer> arr1 = new Vector<>(java.util.Arrays.asList( 1 , 2 , 3 , 4 ));
Vector<Integer> arr2 = new Vector<>(java.util.Arrays.asList( 2 , 4 , 6 , 8 ));
System.out.println(countPairs(arr1));
System.out.println(countPairs(arr2));
}
}
|
Python3
def has_single_distinct_prime_factor(n):
prime_factors = set ()
while n % 2 = = 0 :
prime_factors.add( 2 )
n / / = 2
for i in range ( 3 , int (n * * 0.5 ) + 1 , 2 ):
while n % i = = 0 :
prime_factors.add(i)
n / / = i
if n > 2 :
prime_factors.add(n)
return len (prime_factors) = = 1
def count_pairs(arr):
n = len (arr)
count = 0
for i in range (n):
for j in range (i + 1 , n):
if has_single_distinct_prime_factor(arr[i] * arr[j]):
count + = 1
return count
arr1 = [ 1 , 2 , 3 , 4 ]
arr2 = [ 2 , 4 , 6 , 8 ]
print (count_pairs(arr1))
print (count_pairs(arr2))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool HasSingleDistinctPrimeFactor( int n)
{
HashSet< int > primeFactors = new HashSet< int >();
while (n % 2 == 0) {
primeFactors.Add(2);
n /= 2;
}
for ( int i = 3; i <= Math.Sqrt(n); i += 2) {
while (n % i == 0) {
primeFactors.Add(i);
n /= i;
}
}
if (n > 2) {
primeFactors.Add(n);
}
return primeFactors.Count == 1;
}
static int CountPairs(List< int > arr)
{
int n = arr.Count;
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (HasSingleDistinctPrimeFactor(
arr[i] * arr[j])) {
count++;
}
}
}
return count;
}
static void Main()
{
List< int > arr1 = new List< int >{ 1, 2, 3, 4 };
List< int > arr2 = new List< int >{ 2, 4, 6, 8 };
Console.WriteLine(CountPairs(arr1));
Console.WriteLine(CountPairs(arr2));
}
}
|
Javascript
function hasSingleDistinctPrimeFactor(n) {
let primeFactors = new Set();
while (n % 2 === 0) {
primeFactors.add(2);
n /= 2;
}
for (let i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i === 0) {
primeFactors.add(i);
n /= i;
}
}
if (n > 2) {
primeFactors.add(n);
}
return primeFactors.size === 1;
}
function countPairs(arr) {
let n = arr.length;
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (hasSingleDistinctPrimeFactor(arr[i] * arr[j])) {
count++;
}
}
}
return count;
}
let arr1 = [1, 2, 3, 4];
let arr2 = [2, 4, 6, 8];
console.log(countPairs(arr1));
console.log(countPairs(arr2));
|
The time complexity of has_single_distinct_prime_factor(n) function is O(sqrt(n)), as it iterates over all odd integers up to the square root of n, checking if they divide n.
The time complexity of count_pairs(arr) function is O(n^2) since it has two nested loops that iterate over all pairs of elements in the input array arr.
Overall Time complexity; O(n^2)
Overall auxiliary space: O(n)
Share your thoughts in the comments
Please Login to comment...