数组中所有素数的 XOR 运算(C++)
在这一问题中,我们得到一个包含 n 个元素的数组。我们的任务是输出数组中所有素数的异或值。
让我们举个例子来了解这个问题,
输入 − {2, 6, 8, 9, 11}
输出 −
为了解决这个问题,我们将找出数组中的所有素数,然后进行异或运算以找出结果。为了检查该元素是否是素数,我们将使用筛法算法,然后对所有素数元素进行异或运算。
范例
程序展示了我们解决方案的实现:
#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;
}输出
The xor of all prime number of the array is : 16
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP