
- 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 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
- Related Articles
- Sum of all prime numbers in an array - JavaScript
- Product of all prime numbers in an Array in C++
- Maximum XOR of Two Numbers in an Array in C++
- Sum of XOR of all pairs in an array in C++
- Print prime numbers with prime sum of digits in an array
- Sum of XOR of sum of all pairs in an array in C++
- Maximum value of XOR among all triplets of an array in C++
- Maximum no. of contiguous Prime Numbers in an array in C++
- Sum of all prime numbers in JavaScript
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Python program to print all Prime numbers in an Interval
- Construct an array from XOR of all elements of array except element at same index in C++
- Product of all other numbers an array in JavaScript
- How to Print all Prime Numbers in an Interval using Python?

Advertisements