ในปัญหานี้ เราจะได้รับอาร์เรย์ของ n องค์ประกอบ งานของเราคือพิมพ์ xor ของจำนวนเฉพาะทั้งหมดของอาร์เรย์
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
ป้อนข้อมูล − {2, 6, 8, 9, 11}
ผลผลิต −
เพื่อแก้ปัญหานี้ เราจะหาจำนวนเฉพาะของอาร์เรย์และ xor เพื่อหาผลลัพธ์ ในการตรวจสอบว่าองค์ประกอบนั้นเป็นจำนวนเฉพาะหรือไม่ เราจะใช้อัลกอริทึมของตะแกรงแล้ว xor องค์ประกอบทั้งหมดที่เป็นจำนวนเฉพาะ
ตัวอย่าง
โปรแกรมแสดงการใช้งานโซลูชันของเรา
#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