
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
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,
#include <bits/stdc++.h< using namespace std; bool prime[100005]; void SieveOfEratosthenes(int n) { memset(prime, true, sizeof(prime)); prime[1] = 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[0]); 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
Advertisements