XOR of Sum of every possible pair of an array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n elements. Our task is to generate a sequence of size n*n whose elements are the sum of a pair of all elements of A with itself. And print the xor elements of this sum array formed.

Let’s take an example to understand the problem,

Input − A (1, 4, 5)

Output − 0

Explanation

B (1+1, 1+4, 1+5, 4+1, 4+4, 4+5, 5+1, 5+4, 5+5)
B(2,5,6,5,8,9,6,9,10)
Xor of all values = 2^5^6^5^8^9^6^9^10 = 0.

To solve this problem, we need to know some properties of Xor. The first XOR of a number with the same number is 0. Now, in the newly formed array, there are multiple elements take are the same, elements a[i]+a[j] and a[j]+a[i] are the same so their xors will be 0. So, we are left with 2a[i] elements only so, we will take the xor of all a[i] element and multiply it by two. This will be our final answer.

Example

Program to show the implementation of our algorithm

 Live Demo

#include <iostream>
using namespace std;
int findSumXor(int arr[], int n){
   int XOR = 0 ;
   for (int i = 0; i < n; i++) {
      XOR = XOR ^ arr[i];
   }
   return XOR * 2;
}
int main(){
   int arr[3] = { 2, 4, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The xor of the sum pair of elements of the array is\t"<<findSumXor(arr, n);
   return 0;
}

Output

The xor of the sum pair of elements of the array is 2
raja
Published on 20-Apr-2020 11:36:36
Advertisements