Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 배열에 있는 모든 소수의 XOR


이 문제에서는 n 요소의 배열이 제공됩니다. 우리의 임무는 배열의 모든 소수의 xor를 출력하는 것입니다.

문제를 이해하기 위해 예를 들어보겠습니다.

입력 - {2, 6, 8, 9, 11}

출력 -

이 문제를 해결하기 위해 배열의 모든 소수를 찾고 xor하여 결과를 찾습니다. 요소가 소수인지 확인하기 위해 sieve 알고리즘을 사용한 다음 소수인 모든 요소를 ​​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