XOR of Sum of every possible pair of an array
Given an array A of size n. the task is to generate a new sequence B with size N^2 having elements sum of every pair of array A and find the xor value of the sum of all the pairs formed.
Note: Here (A[i], A[i]), (A[i], A[j]), (A[j], A[i]) all are considered as different pairs.
Examples:
Input: arr[] = {1, 5, 6}
Output: 4
B[3*3] = { 1+1, 1+5, 1+6, 5+1, 5+5, 5+6, 6+1, 6+5, 6+6}
B[9] = { 2, 6, 7, 6, 10, 11, 7, 11, 12}
So, 2 ^ 6 ^ 7 ^ 6 ^ 10 ^ 11 ^ 7 ^ 6 ^ 11 ^ 12 = 4
Input arr[]:{1, 2}
Output :6
A Naive approach is to run two loops. Consider each and every pair, take their sum, and calculate the xor value of the sum of all the pairs.
An Efficient approach is based upon the fact that xor of the same values is 0.
All the pairs like (a[i], a[j]) and (a[j], a[i]) will have same sum. So, their xor values will be 0. Only the pairs like (a[i], a[i]) will give the different result. So, take the xor of all the elements of the given array and multiply it by 2.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int findXor( 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] = { 1, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findXor(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findXor( int arr[], int n)
{
int xoR = 0 ;
for ( int i = 0 ; i < n; i++) {
xoR = xoR ^ arr[i];
}
return xoR * 2 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 5 , 6 };
int n = arr.length;
System.out.println( findXor(arr, n));
}
}
|
Python3
def findXor(arr,n):
xoR = 0 ;
for i in range ( 0 , n ) :
xoR = xoR ^ arr[i]
return xoR * 2
arr = [ 1 , 5 , 6 ]
n = len (arr)
print (findXor(arr, n))
|
C#
using System;
class GFG {
static int findXor( int []arr, int n)
{
int xoR = 0;
for ( int i = 0; i < n; i++) {
xoR = xoR ^ arr[i];
}
return xoR * 2;
}
public static void Main ()
{
int []arr = { 1, 5, 6 };
int n = arr.Length;
Console.WriteLine( findXor(arr, n));
}
}
|
PHP
<?php
function findXor( $arr , $n )
{
$xoR = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$xoR = $xoR ^ $arr [ $i ];
}
return $xoR * 2;
}
$arr = array (1, 5, 6);
$n = count ( $arr );
echo findXor( $arr , $n );
?>
|
Javascript
<script>
function findXor(arr, n)
{
let xoR = 0;
for (let i = 0; i < n; i++) {
xoR = xoR ^ arr[i];
}
return xoR * 2;
}
let arr = [ 1, 5, 6 ];
let n = arr.length;
document.write(findXor(arr, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...