# XOR of all Prime numbers in an Array in C++

In this problem, we are given an array of n elements. Our task is to print xor of all prime numbers of the array.

Let’s take an example to understand the problem,

Input − {2, 6, 8, 9, 11}

Output

To solve this problem, we will find all the prime numbers of the array and the xor them to find the result. To check if the element is prime or not, we will use sieve’s algorithm and then xor all elements that are prime.

## Example

Program to show the implementation of our solution,

Live Demo

#include <bits/stdc++.h<
using namespace std;
bool prime;
void SieveOfEratosthenes(int n) {
memset(prime, true, sizeof(prime));
prime = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
}
int findXorOfPrimes(int arr[], int n){
SieveOfEratosthenes(100005);
int result = 0;
for (int i = 0; i < n; i++) {
if (prime[arr[i]])
result = result ^ arr[i];
}
return result;
}
int main() {
int arr[] = { 4, 3, 2, 6, 100, 17 };
int n = sizeof(arr) / sizeof(arr);
cout<<"The xor of all prime number of the array is : "<<findXorOfPrimes(arr, n);
return 0;
}

## Output

The xor of all prime number of the array is : 16