
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of XOR of All Pairs in an Array in C++
In this problem, we are given an array arr[] of size n. Our task is to create a program to find the sum of XOR of sum of all pairs in an array.
Let’s see an example to understand the problem,
Input: arr[5, 7, 9]
Output: 22
Explanation:
(5+5) ^ (5+7) ^ (5+9) ^ (7+5) ^ (7+7) ^ (7+9) ^ (9+5) ^ (9+7) ^ (9+9) = 22
A simple solution to the problem is by using a nested loop. And creating all possible pairs from the array. And calculate the XOR of the sum of each pair.
Algorithm:
Initialise XorSum = 0
Step 1: iterate from 0 to n. Follow:
Step 1.1: iterate from 0 to n. Follow
Step 1.1.1: Update XorSum i.e. XorSum = XorSum ^ (arr[i]+arr[j]).
Step 2: return sum
Program to illustrate the working of our code
Example
#include <iostream> using namespace std; int findSumXORPair(int arr[], int n) { int XorSum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) XorSum = XorSum^(arr[i]+arr[j]); return XorSum; } int main() { int arr[] = {5, 7, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"XOR of sum of all pairs in an array is "<<findSumXORPair(arr, n); return 0; }
Output
XOR of sum of all pairs in an array is 22
This solution is not efficient as its time complexity is of the order n2.
An efficient solution is using the properties of XOR. To solve the problem, we will calculate the XOR of all elements of the array and then multiply it by two.
Algorithm:
Initialize XorSum = 0
Step 1: Iterate from 0 to n.
Step 1.1: update XorSum i.e. XorSum = XorSum ^ arr[i]
Step 2: double the sum and return it.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int findSumXORPair(int arr[], int n) { int XorSum = 0; for (int i = 0; i < n; i++) XorSum = XorSum^arr[i]; XorSum = 2*XorSum; return XorSum; } int main() { int arr[] = {5, 7, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"XOR of sum of all pairs in an array is "<<findSumXORPair(arr, n); return 0; }
Output
XOR of sum of all pairs in an array is 22