
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Product of all prime numbers in an Array in C++
- Sum of all prime numbers in an array - JavaScript
- 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
- Maximum no. of contiguous Prime Numbers in an array in C++
- 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++
- 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?
- C Program to Minimum and Maximum prime numbers in an array
- Product of all the Composite Numbers in an array in C++
- Find All Numbers Disappeared in an Array in C++
- Construct an array from XOR of all elements of array except element at same index in C++
Advertisements