
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
XOR of Sum of every possible pair of an array in C++
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
#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
- Related Articles
- Maximum possible XOR of every element in an array with another array in C++
- Sum of XOR of sum of all pairs in an array in C++
- Sum of XOR of all possible subsets in C++
- Sum of XOR of all pairs in an array in C++
- Find a number which give minimum sum when XOR with every number of array of integer in Python
- Find a number which give minimum sum when XOR with every number of array of integer in C++
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript
- C++ Largest Subset with Sum of Every Pair as Prime
- Rearrange an array to minimize sum of product of consecutive pair elements in C++
- Reduce an array to the sum of every nth element - JavaScript
- Finding sum of every nth element of array in JavaScript
- XOR every element of a masked array by a given scalar value in Python
- XOR a given scalar value with every element of a masked array in Python
- Achieving maximum possible pair sum in JavaScript
- Sum of XOR of all subarrays in C++
