# Count pairs whose product contains single distinct prime factor

• Difficulty Level : Hard
• Last Updated : 09 Jun, 2021

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 * arr = (1 * 2) = 2. Therefore, the single distinct prime factor is 2.
arr * arr = (1 * 3) = 3. Therefore, the single distinct prime factor is 3.
arr * arr = (1 * 4) = 22 Therefore, the single distinct prime factor is 2.
arr * arr = (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++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;`  `// Function to find a single``// distinct prime factor of N``int` `singlePrimeFactor(``int` `N)``{``    ` `    ``// Stores distinct``    ``// prime factors of N``    ``unordered_set<``int``>``              ``disPrimeFact;``  ` `  ` `    ``// Calculate prime factor of N``    ``for` `(``int` `i = 2; i * i <= N; ++i) {``        ` `        ` `        ``// Calculate distinct``        ``// prime factor``        ``while` `(N % i == 0) {``            ` `            ` `            ``// Insert i into``            ``// disPrimeFact``            ``disPrimeFact.insert(i);``            ` `            ` `            ``// Update N``            ``N /= i;``        ``}``    ``}``   ` `   ` `    ``// If N is not equal to 1``    ``if` `(N != 1)``    ``{``        ` `        ``// Insert N into``        ``// disPrimeFact``        ``disPrimeFact.insert(N);``    ``}``    ` `    ` `    ``// If N contains a single``    ``// distinct prime factor``    ``if` `(disPrimeFact.size() == 1) {``        ` `        ` `        ``// Return single distinct``        ``// prime factor of N``        ``return` `*disPrimeFact.begin();``    ``}   ``    ` `    ` `    ``// If N contains more than one``    ``// distinct prime factor   ``    ``return` `-1;``}`  `// Function to count pairs in the array``// whose product contains only``// single distinct prime factor``int` `cntsingleFactorPair(``int` `arr[], ``int` `N)``{``    ` `   ``// Stores count of 1s``   ``// in the array``    ``int` `countOf1 = 0;``    ` `    ` `    ``// mp[i]: Stores count of array elements``    ``// whose distinct prime factor is only i``    ``unordered_map<``int``, ``int``> mp;``    ` `    ` `    ``// Traverse the array arr[]``    ``for` `(``int` `i = 0; i < N; i++) {``        ` `        ` `        ``// If current element is 1``        ``if``(arr[i] == 1)``        ``{``            ``countOf1++;``            ``continue``;``        ``}``      ` `      ` `        ``// Store distinct``        ``// prime factor of arr[i]``        ``int` `factorValue``          ``= singlePrimeFactor(arr[i]);``        ` `        ` `        ``// If arr[i] contains more``        ``// than one prime factor``        ``if` `(factorValue == -1) {``            ``continue``;``        ``}``        ` `        ` `        ``// If arr[i] contains``        ``// a single prime factor``        ``else` `{``            ``mp[factorValue]++;``        ``}``    ``}``      ` `      ` `    ``// Stores the count of pairs whose``    ``// product of elements contains only``    ``// a single distinct prime factor``    ``int` `res = 0;``  ` `  ` `    ``// Traverse the map mp[]``    ``for` `(``auto` `it : mp) { ``        ` `        ` `        ``// Stores count of array elements``        ``// whose prime factor is (it.first)``        ``int` `X = it.second;``        ` `        ` `        ``// Update res``        ``res += countOf1 * X +``              ``(X * (X - 1) ) / 2;``    ``}``    ` `    ``return` `res;``}`  `// Driver Code``int` `main()``{` `    ``int` `arr[] = { 1, 2, 3, 4 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``cout << cntsingleFactorPair(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;``class` `GFG{` `// Function to find a single``// distinct prime factor of N``static` `int` `singlePrimeFactor(``int` `N)``{``  ``// Stores distinct``  ``// prime factors of N``  ``HashSet disPrimeFact =``                   ``new` `HashSet<>();` `  ``// Calculate prime factor of N``  ``for` `(``int` `i = ``2``;``           ``i * i <= N; ++i)``  ``{``    ``// Calculate distinct``    ``// prime factor``    ``while` `(N % i == ``0``)``    ``{``      ``// Insert i into``      ``// disPrimeFact``      ``disPrimeFact.add(i);` `      ``// Update N``      ``N /= i;``    ``}``  ``}` `  ``// If N is not equal to 1``  ``if` `(N != ``1``)``  ``{``    ``// Insert N into``    ``// disPrimeFact``    ``disPrimeFact.add(N);``  ``}` `  ``// If N contains a single``  ``// distinct prime factor``  ``if` `(disPrimeFact.size() == ``1``)``  ``{``    ``// Return single distinct``    ``// prime factor of N``    ``for``(``int` `i : disPrimeFact)``      ``return` `i;``  ``}` `  ``// If N contains more than``  ``// one distinct prime factor   ``  ``return` `-``1``;``}`  `// Function to count pairs in``// the array whose product``// contains only single distinct``// prime factor``static` `int` `cntsingleFactorPair(``int` `arr[],``                               ``int` `N)``{  ``  ``// Stores count of 1s``  ``// in the array``  ``int` `countOf1 = ``0``;` `  ``// mp[i]: Stores count of array``  ``// elements whose distinct prime``  ``// factor is only i``  ``HashMap mp = ``new` `HashMap();` `  ``// Traverse the array arr[]``  ``for` `(``int` `i = ``0``; i < N; i++)``  ``{``    ``// If current element is 1``    ``if``(arr[i] == ``1``)``    ``{``      ``countOf1++;``      ``continue``;``    ``}` `    ``// Store distinct``    ``// prime factor of arr[i]``    ``int` `factorValue =``        ``singlePrimeFactor(arr[i]);` `    ``// If arr[i] contains more``    ``// than one prime factor``    ``if` `(factorValue == -``1``)``    ``{``      ``continue``;``    ``}` `    ``// If arr[i] contains``    ``// a single prime factor``    ``else``    ``{``      ``if``(mp.containsKey(factorValue))``        ``mp.put(factorValue,``        ``mp.get(factorValue) + ``1``);``      ``else``        ``mp.put(factorValue, ``1``);``    ``}``  ``}` `  ``// Stores the count of pairs whose``  ``// product of elements contains only``  ``// a single distinct prime factor``  ``int` `res = ``0``;` `  ``// Traverse the map mp[]``  ``for` `(Map.Entry it :``       ``mp.entrySet())``  ``{``    ``// Stores count of array``    ``// elements whose prime``    ``// factor is (it.first)``    ``int` `X = it.getValue();` `    ``// Update res``    ``res += countOf1 * X +``           ``(X * (X - ``1``) ) / ``2``;``  ``}` `  ``return` `res;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``  ``int` `arr[] = {``1``, ``2``, ``3``, ``4``};``  ``int` `N = arr.length;``  ``System.out.print(``         ``cntsingleFactorPair(arr, N));``}``}` `// This code is contributed by gauravrajput1`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to find a single``# distinct prime factor of N``def` `singlePrimeFactor(N):``    ` `    ``# Stores distinct``    ``# prime factors of N``    ``disPrimeFact ``=` `{}``    ` `    ``# Calculate prime factor of N``    ``for` `i ``in` `range``(``2``, N ``+` `1``):``        ``if` `i ``*` `i > N:``            ``break``        ` `        ``# Calculate distinct``        ``# prime factor``        ``while` `(N ``%` `i ``=``=` `0``):``            ` `            ``# Insert i into``            ``# disPrimeFact``            ``disPrimeFact[i] ``=` `1``            ` `            ``# Update N``            ``N ``/``/``=` `i` `    ``# If N is not equal to 1``    ``if` `(N !``=` `1``):``        ` `        ``# Insert N into``        ``# disPrimeFact``        ``disPrimeFact[N] ``=` `1``        ` `    ``# If N contains a single``    ``# distinct prime factor``    ``if` `(``len``(disPrimeFact) ``=``=` `1``):``        ` `        ``# Return single distinct``        ``# prime factor of N``        ``return` `list``(disPrimeFact.keys())[``0``]``        ` `    ``# If N contains more than one``    ``# distinct prime factor``    ``return` `-``1` `# Function to count pairs in the array``# whose product contains only``# single distinct prime factor``def` `cntsingleFactorPair(arr, N):``    ` `    ``# Stores count of 1s``    ``# in the array``    ``countOf1 ``=` `0` `    ``# mp[i]: Stores count of array elements``    ``# whose distinct prime factor is only i``    ``mp ``=` `{}` `    ``# Traverse the array arr[]``    ``for` `i ``in` `range``(N):``        ` `        ``# If current element is 1``        ``if` `(arr[i] ``=``=` `1``):``            ``countOf1 ``+``=` `1``            ``continue` `        ``# Store distinct``        ``# prime factor of arr[i]``        ``factorValue ``=` `singlePrimeFactor(arr[i])` `        ``# If arr[i] contains more``        ``# than one prime factor``        ``if` `(factorValue ``=``=` `-``1``):``            ``continue``        ` `        ``# If arr[i] contains``        ``# a single prime factor``        ``else``:``            ``mp[factorValue] ``=` `mp.get(factorValue, ``0``) ``+` `1` `    ``# Stores the count of pairs whose``    ``# product of elements contains only``    ``# a single distinct prime factor``    ``res ``=` `0` `    ``# Traverse the map mp[]``    ``for` `it ``in` `mp:``        ` `        ``# Stores count of array elements``        ``# whose prime factor is (it.first)``        ``X ``=` `mp[it]` `        ``# Update res``        ``res ``+``=` `countOf1 ``*` `X ``+` `(X ``*` `(X ``-` `1``) ) ``/``/` `2` `    ``return` `res` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``4` `]``    ``N ``=` `len``(arr)``    ` `    ``print``(cntsingleFactorPair(arr, N))` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG{` `// Function to find a single``// distinct prime factor of N``static` `int` `singlePrimeFactor(``int` `N)``{``  ``// Stores distinct``  ``// prime factors of N``  ``HashSet<``int``> disPrimeFact =``          ``new` `HashSet<``int``>();` `  ``// Calculate prime factor of N``  ``for` `(``int` `i = 2;``           ``i * i <= N; ++i)``  ``{``    ``// Calculate distinct``    ``// prime factor``    ``while` `(N % i == 0)``    ``{``      ``// Insert i into``      ``// disPrimeFact``      ``disPrimeFact.Add(i);` `      ``// Update N``      ``N /= i;``    ``}``  ``}` `  ``// If N is not equal to 1``  ``if``(N != 1)``  ``{``    ``// Insert N into``    ``// disPrimeFact``    ``disPrimeFact.Add(N);``  ``}` `  ``// If N contains a single``  ``// distinct prime factor``  ``if` `(disPrimeFact.Count == 1)``  ``{``    ``// Return single distinct``    ``// prime factor of N``    ``foreach``(``int` `i ``in` `disPrimeFact)``      ``return` `i;``  ``}` `  ``// If N contains more than``  ``// one distinct prime factor   ``  ``return` `-1;``}`  `// Function to count pairs in``// the array whose product``// contains only single distinct``// prime factor``static` `int` `cntsingleFactorPair(``int` `[]arr,``                               ``int` `N)``{  ``  ``// Stores count of 1s``  ``// in the array``  ``int` `countOf1 = 0;` `  ``// mp[i]: Stores count of array``  ``// elements whose distinct prime``  ``// factor is only i``  ``Dictionary<``int``,``             ``int``> mp =``             ``new` `Dictionary<``int``,``                            ``int``>();` `  ``// Traverse the array arr[]``  ``for` `(``int` `i = 0; i < N; i++)``  ``{``    ``// If current element is 1``    ``if``(arr[i] == 1)``    ``{``      ``countOf1++;``      ``continue``;``    ``}` `    ``// Store distinct``    ``// prime factor of arr[i]``    ``int` `factorValue =``        ``singlePrimeFactor(arr[i]);` `    ``// If arr[i] contains more``    ``// than one prime factor``    ``if` `(factorValue == -1)``    ``{``      ``continue``;``    ``}` `    ``// If arr[i] contains``    ``// a single prime factor``    ``else``    ``{``      ``if``(mp.ContainsKey(factorValue))``        ``mp[factorValue] = mp[factorValue] + 1;``      ``else``        ``mp.Add(factorValue, 1);``    ``}``  ``}` `  ``// Stores the count of pairs whose``  ``// product of elements contains only``  ``// a single distinct prime factor``  ``int` `res = 0;` `  ``// Traverse the map mp[]``  ``foreach``(KeyValuePair<``int``,``                       ``int``> ele1 ``in` `mp)``  ``{``    ``// Stores count of array``    ``// elements whose prime``    ``// factor is (it.first)``    ``int` `X = ele1.Value;` `    ``// Update res``    ``res += countOf1 * X +``           ``(X * (X - 1) ) / 2;``  ``}` `  ``return` `res;``}` `// Driver Code``public` `static` `void` `Main()``{``  ``int` `[]arr = {1, 2, 3, 4};``  ``int` `N = arr.Length;``  ``Console.WriteLine(``         ``cntsingleFactorPair(arr, N));``}``}` `// This code is contributed by bgangwar59`

## Javascript

 ``

Output:

`4`

Time Complexity: O(N√X), where X is the maximum element of the given array.
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up