Open In App

Count the XOR-friendly pairs

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[], the task is to count the number of XOR-friendly pairs.

An XOR-friendly pair is defined as a pair of elements for which the greatest of the prime factors of the XOR of the two elements of the pair is greater than the difference of elements of the pair itself.

Examples:

Input: A[] = {6, 8, 4} 
Output: 1
Explanation: For all pairs:
Pair: 6 8 (diff = 2), XOR: 14, pfs:  2  7 (7 > 2) 
Pair: 6 4 (diff = 2), XOR: 2, pfs:  2        
Pair: 8 4 (diff = 4), XOR: 12, pfs:  2  2  3   

Only for pair (6, 8) the greatest prime factor 7 is greater than the difference 2

Input: A[] = {9, 6, 4, 8}
Output: 3
Explanation: For all pairs:
Pair: 9 6 (diff = 3), XOR: 15, pfs: 3 5
Pair: 9 4 (diff = 5), XOR: 13, pfs: 13
Pair: 9 8 (diff = 1), XOR: 1, pfs: No prime factors for 1
Pair: 6 4 (diff = 2), XOR: 2, pfs: 2
Pair: 6 8 (diff = 2), XOR: 14, pfs: 2 7
Pair: 4 8 (diff = 4)   XOR: 12, pfs: 2 3 

For pairs (9, 6), (9, 4), (6, 8) the greatest prime factor is greater than the difference of the pair

Approach: To solve the problem follow the below idea:

This solution is simple, using two for-loops we iterate through all the pairs, and for each pair, we find their difference and XOR. Then using the square root method we find all prime factors of the XOR and store them in an array then find the greatest of all the prime numbers. Now check if the greatest prime factor of the XOR of the pair of elements is greater than the difference of the pair of elements if it is then we have found one such pair. Similarly, we find all such pairs.

Follow the below steps to solve the problem:

  • Define a data structure: vector of pairs that will store the required pairs.
  • Two nested loops are used to iterate through all the pairs of the array.
  • For each pair compute the bitwise XOR then find all prime factors of the XOR and store them in another array (for this solution the square root method of finding prime factors has been used) 
  • Find the largest of the prime factors from the array created in the above step.
  • check if the largest prime factor is greater than the difference of the pair, if it is then push the pair into the data structure.
  • When both the loops end return the size of the data structure as it will contain only those pairs whose difference is smaller than the greatest prime factor of their XOR.

Below is the implementation of the above approach:-

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to generate a vector
// of prime factors
vector<int> numOfPrimeFacts(int n)
{
 
    // Vector to store the prime factors
    vector<int> a;
 
    // If n = 1 then prime factors are 0
    if (n == 1) {
        a.push_back(0);
        return a;
    }
 
    for (int i = 2; (i * i) <= n; i++) {
        while (n % i == 0) {
            a.push_back(i);
            n = n / i;
        }
    }
 
    // Case when n is prime
    if (n > 1)
        a.push_back(n);
 
    return a;
}
 
// Function to find the greatest of the
// prime factors
int greatestPrimeFact(vector<int> v)
{
    int ans = 0;
    for (int i = 0; i < v.size(); i++)
        if (v[i] > ans)
            ans = v[i];
    return ans;
}
 
// Function to return the pair whose XOR
// has least number of prime factors
vector<pair<int, int> > returnPair(int arr[], int n)
{
 
    // Store the pairs
    vector<pair<int, int> > vec;
 
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            pair<int, int> p;
            p.first = arr[i];
            p.second = arr[j];
 
            // XOR of pair
            int val = arr[i] ^ arr[j];
 
            // Difference of pair
            int diffOfPair = abs(arr[i] - arr[j]);
 
            // Vector of prime factors
            // of val
            vector<int> a = numOfPrimeFacts(val);
 
            // Greatest of the
            // prime factors
            int largestPrimeFact = greatestPrimeFact(a);
 
            if (largestPrimeFact > diffOfPair)
                vec.push_back(p);
        }
    }
 
    return vec;
}
 
// Driver's Code
int main()
{
    int arr[] = { 9, 6, 4, 8 };
    int n = 4;
 
    vector<pair<int, int> > vec = returnPair(arr, n);
 
    cout << "The number of such pairs is " << vec.size()
         << '\n';
    cout << "The pair(s) is/are :\n";
 
    cout << "[";
    for (int i = 0; i < vec.size(); i++) {
        cout << " ( " << vec[i].first << ", "
             << vec[i].second << " ) ";
    }
    cout << "]";
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class Pair<U, V> {
    public final U first;
    public final V second;
 
    public Pair(U first, V second) {
        this.first = first;
        this.second = second;
    }
}
 
class GFG {
     
    // Utility function to generate a list
    // of prime factors
    static List<Integer> numOfPrimeFacts(int n) {
 
        // List to store the prime factors
        List<Integer> a = new ArrayList<Integer>();
 
        // If n = 1 then prime factors are 0
        if (n == 1) {
            a.add(0);
            return a;
        }
 
        for (int i = 2; (i * i) <= n; i++) {
            while (n % i == 0) {
                a.add(i);
                n = n / i;
            }
        }
 
        // Case when n is prime
        if (n > 1)
            a.add(n);
 
        return a;
    }
 
    // Function to find the greatest of the
    // prime factors
    static int greatestPrimeFact(List<Integer> v) {
        int ans = 0;
        for (int i = 0; i < v.size(); i++)
            if (v.get(i) > ans)
                ans = v.get(i);
        return ans;
    }
 
    // Function to return the pair whose XOR
    // has least number of prime factors
    static List<Pair<Integer, Integer>> returnPair(int[] arr, int n) {
 
        // Store the pairs
        List<Pair<Integer, Integer>> vec = new ArrayList<>();
 
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                Pair<Integer, Integer> p = new Pair<Integer, Integer>(arr[i], arr[j]);
 
                // XOR of pair
                int val = arr[i] ^ arr[j];
 
                // Difference of pair
                int diffOfPair = Math.abs(arr[i] - arr[j]);
 
                // List of prime factors
                // of val
                List<Integer> a = numOfPrimeFacts(val);
 
                // Greatest of the
                // prime factors
                int largestPrimeFact = greatestPrimeFact(a);
 
                if (largestPrimeFact > diffOfPair)
                    vec.add(p);
            }
        }
 
        return vec;
    }
 
    // Driver's Code
    public static void main(String[] args) {
        int[] arr = { 9, 6, 4, 8 };
        int n = 4;
 
        List<Pair<Integer, Integer>> vec = returnPair(arr, n);
 
        System.out.println("The number of such pairs is " + vec.size());
        System.out.println("The pair(s) is/are :");
 
        System.out.print("[");
        for (int i = 0; i < vec.size(); i++) {
            System.out.print(" ( " + vec.get(i).first + ", "
                    + vec.get(i).second + " ) ");
        }
        System.out.println("]");
    }
}
 
// This code is contributed by Prasad Kandekar(prasad264)


C#




// C# code implementation:
 
using System;
using System.Collections.Generic;
 
public class Pair<U, V> {
    public readonly U first;
    public readonly V second;
 
    public Pair(U first, V second)
    {
        this.first = first;
        this.second = second;
    }
}
 
public class GFG {
 
    // Utility function to generate a list of prime factors
    static List<int> NumOfPrimeFacts(int n)
    {
        // List to store the prime factors
        List<int> a = new List<int>();
 
        // If n = 1 then prime factors are 0
        if (n == 1) {
            a.Add(0);
            return a;
        }
 
        for (int i = 2; (i * i) <= n; i++) {
            while (n % i == 0) {
                a.Add(i);
                n = n / i;
            }
        }
 
        // Case when n is prime
        if (n > 1)
            a.Add(n);
 
        return a;
    }
 
    // Function to find the greatest of the prime factors
    static int GreatestPrimeFact(List<int> v)
    {
        int ans = 0;
        for (int i = 0; i < v.Count; i++)
            if (v[i] > ans)
                ans = v[i];
        return ans;
    }
 
    // Function to return the pair whose XOR has least
    // number of prime factors
    static List<Pair<int, int> > ReturnPair(int[] arr,
                                            int n)
    {
        // Store the pairs
        List<Pair<int, int> > vec
            = new List<Pair<int, int> >();
 
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                Pair<int, int> p
                    = new Pair<int, int>(arr[i], arr[j]);
 
                // XOR of pair
                int val = arr[i] ^ arr[j];
 
                // Difference of pair
                int diffOfPair = Math.Abs(arr[i] - arr[j]);
 
                // List of prime factors of val
                List<int> a = NumOfPrimeFacts(val);
 
                // Greatest of the prime factors
                int largestPrimeFact = GreatestPrimeFact(a);
 
                if (largestPrimeFact > diffOfPair)
                    vec.Add(p);
            }
        }
 
        return vec;
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 9, 6, 4, 8 };
        int n = 4;
 
        List<Pair<int, int> > vec = ReturnPair(arr, n);
 
        Console.WriteLine("The number of such pairs is "
                          + vec.Count);
        Console.WriteLine("The pair(s) is/are :");
 
        Console.Write("[");
        for (int i = 0; i < vec.Count; i++) {
            Console.Write(" ( " + vec[i].first + ", "
                          + vec[i].second + " ) ");
        }
        Console.WriteLine("]");
    }
}
 
// This code is contributed by sankar.


Python3




# Python program for the above approach
 
import math
 
# Utility function to generate a list of prime factors
def numOfPrimeFacts(n):
    # List to store the prime factors
    a = []
    # If n = 1 then prime factors are 0
    if n == 1:
        a.append(0)
        return a
    for i in range(2, int(math.sqrt(n))+1):
        while n % i == 0:
            a.append(i)
            n = n // i
    # Case when n is prime
    if n > 1:
        a.append(n)
    return a
 
# Function to find the greatest of the prime factors
def greatestPrimeFact(v):
    ans = 0
    for i in range(len(v)):
        if v[i] > ans:
            ans = v[i]
    return ans
 
# Function to return the pair whose XOR has least number
# of prime factors
def returnPair(arr, n):
    # Store the pairs
    vec = []
    for i in range(n):
        for j in range(i + 1, n):
            p = (arr[i], arr[j])
            # XOR of pair
            val = arr[i] ^ arr[j]
            # Difference of pair
            diffOfPair = abs(arr[i] - arr[j])
            # List of prime factors of val
            a = numOfPrimeFacts(val)
            # Greatest of the prime factors
            largestPrimeFact = greatestPrimeFact(a)
            if largestPrimeFact > diffOfPair:
                vec.append(p)
    return vec
 
# Driver's Code
if __name__ == "__main__":
    arr = [9, 6, 4, 8]
    n = len(arr)
    vec = returnPair(arr, n)
    print("The number of such pairs is", len(vec))
    print("The pair(s) is/are :")
    print("[", end="")
    for i in range(len(vec)):
        print(" (", vec[i][0], ", ", vec[i][1], ") ", end="")
    print("]")
 
# This code is contributed by karthik.


Javascript




// JavaScript program for the above approach
 
class Pair {
constructor(first, second) {
this.first = first;
this.second = second;
}
}
 
// Utility function to generate a list
// of prime factors
function numOfPrimeFacts(n) {
 
// List to store the prime factors
let a = [];
 
// If n = 1 then prime factors are 0
if (n === 1) {
a.push(0);
return a;
}
 
for (let i = 2; (i * i) <= n; i++) {
while (n % i === 0) {
a.push(i);
n = n / i;
}
}
 
// Case when n is prime
if (n > 1)
a.push(n);
 
return a;
}
 
// Function to find the greatest of the
// prime factors
function greatestPrimeFact(v) {
let ans = 0;
for (let i = 0; i < v.length; i++)
if (v[i] > ans)
ans = v[i];
return ans;
}
 
// Function to return the pair whose XOR
// has least number of prime factors
function returnPair(arr, n) {
 
// Store the pairs
let vec = [];
 
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let p = new Pair(arr[i], arr[j]);
  // XOR of pair
  let val = arr[i] ^ arr[j];
 
  // Difference of pair
  let diffOfPair = Math.abs(arr[i] - arr[j]);
 
  // List of prime factors
  // of val
  let a = numOfPrimeFacts(val);
 
  // Greatest of the
  // prime factors
  let largestPrimeFact = greatestPrimeFact(a);
 
  if (largestPrimeFact > diffOfPair)
    vec.push(p);
}
}
 
return vec;
}
 
// Driver's Code
let arr = [9, 6, 4, 8];
let n = 4;
 
let vec = returnPair(arr, n);
 
console.log("The number of such pairs is " + vec.length);
console.log("The pair(s) is/are :");
 
let outputStr = "[";
 
for (let i = 0; i < vec.length; i++) {
outputStr += " ( " + vec[i].first + ", " + vec[i].second + " ) ";
}
 
outputStr += "]";
console.log(outputStr);


Output

The number of such pairs is 3
The pair(s) is/are :
[ ( 9, 6 )  ( 9, 4 )  ( 6, 8 ) ]

Time Complexity: O(n^2 x  sqrt(n) * k  + n), where n is the XOR of the pair, and k is the number of prime factors.
Auxiliary Space: O(n + k)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads