XOR of elements in an array having prime frequency

Given an array arr[] of N elements, the task is to find the xor of the elements which have prime frequencies in the array. Note that 1 is neither prime nor composite.

Examples:

Input: arr[] = {5, 4, 6, 5, 4, 6}
Output: 7
All the elements appear 2 times which is a prime
So, 5 ^ 4 ^ 6 = 7



Input: arr[] = {1, 2, 3, 3, 2, 3, 2, 3, 3}
Output: 1
Only 2 and 3 appears prime number of times i.e. 3 and 5 respectively.
So, 2 ^ 3 = 1

Approach:

  • Traverse the array and store the frequencies of all the elements in a map.
  • Build Sieve of Eratosthenes which will be used to test the primality of a number in O(1) time.
  • Calculate the xor of elements having prime frequency using the Sieve array calculated in the previous step.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to create Sieve to check primes
void SieveOfEratosthenes(bool prime[], int p_size)
{
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;
  
    for (int p = 2; p * p <= p_size; p++) {
  
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {
  
            // Update all multiples of p,
            // set them to non-prime
            for (int i = p * 2; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}
  
// Function to return the xor of elements
// in an array having prime frequency
int xorPrimeFreq(int arr[], int n)
{
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
  
    SieveOfEratosthenes(prime, n + 1);
  
    int i, j;
  
    // Map is used to store
    // element frequencies
    unordered_map<int, int> m;
    for (i = 0; i < n; i++)
        m[arr[i]]++;
  
    long xorVal = 0;
  
    // Traverse the map using iterators
    for (auto it = m.begin(); it != m.end(); it++) {
  
        // Count the number of elements
        // having prime frequencies
        if (prime[it->second]) {
            xorVal ^= it->first;
        }
    }
  
    return xorVal;
}
  
// Driver code
int main()
{
    int arr[] = { 5, 4, 6, 5, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << xorPrimeFreq(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find xor of elements 
// in an array having prime frequency 
import java.util.*; 
  
class GFG 
  
    // Function to create Sieve to check primes 
    static void SieveOfEratosthenes(boolean prime[], 
                                        int p_size) 
    
        // False here indicates 
        // that it is not prime 
        prime[0] = false
        prime[1] = false
      
        for (int p = 2; p * p <= p_size; p++) 
        
      
            // If prime[p] is not changed, 
            // then it is a prime 
            if (prime[p]) 
            
      
                // Update all multiples of p, 
                // set them to non-prime 
                for (int i = p * 2
                         i <= p_size; i += p) 
                    prime[i] = false
            
        
    
      
    // Function to return the xor of elements 
    // in an array having prime frequency 
    static int xorOfElements(int arr[], int n) 
    
        boolean prime[] = new boolean[n + 1]; 
        Arrays.fill(prime, true); 
      
        SieveOfEratosthenes(prime, n + 1); 
      
        int i, j; 
      
        // Map is used to store 
        // element frequencies 
        HashMap<Integer, 
                Integer> m = new HashMap<>(); 
        for (i = 0; i < n; i++) 
        
            if(m.containsKey(arr[i])) 
                m.put(arr[i], m.get(arr[i]) + 1); 
            else
                m.put(arr[i], 1); 
        
      
        int xor = 0
      
        // Traverse the map 
        for (Map.Entry<Integer, 
                       Integer> entry : m.entrySet()) 
        
            int key = entry.getKey(); 
            int value = entry.getValue(); 
              
            // xor the elements 
            // having prime frequencies 
            if (prime[value]) 
            
                xor ^= (key); 
            
        
      
        return xor; 
    
      
    // Driver code 
    public static void main(String args[]) 
    
        int arr[] = { 5, 4, 6, 5, 4, 6 }; 
        int n = arr.length; 
      
        System.out.println(xorOfElements(arr, n)); 
    
  
// This code is contributed by NikhilRathor

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
from math import sqrt
  
# Function to create Sieve to check primes 
def SieveOfEratosthenes(prime, p_size) :
  
    # False here indicates 
    # that it is not prime 
    prime[0] = False
    prime[1] = False
  
    for p in range(2, int(sqrt(p_size)) + 1) :
  
        # If prime[p] is not changed, 
        # then it is a prime 
        if (prime[p]) :
  
            # Update all multiples of p, 
            # set them to non-prime 
            for i in range(p * 2, p_size + 1, p) : 
                prime[i] = False
                  
    return prime
      
# Function to return the xor of elements 
# in an array having prime frequency 
def xorPrimeFreq( arr, n) : 
    prime = [True] * (n + 1); 
  
    prime = SieveOfEratosthenes(prime, n + 1); 
  
    # Map is used to store 
    # element frequencies 
    m = dict.fromkeys(arr, 0);
      
    for i in range(n) :
        m[arr[i]] += 1
  
    xorVal = 0
  
    # Traverse the map using iterators 
    for key,value in m.items() :
  
        # Count the number of elements 
        # having prime frequencies 
        if (prime[value]) :
            xorVal ^= key; 
  
    return xorVal; 
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 5, 4, 6, 5, 4, 6 ]; 
      
    n = len(arr); 
  
    print(xorPrimeFreq(arr, n)); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find xor of elements 
// in an array having prime frequency 
using System;
using System.Collections.Generic;    
  
class GFG 
  
    // Function to create Sieve to check primes 
    static void SieveOfEratosthenes(bool []prime, 
                                    int p_size) 
    
        // False here indicates 
        // that it is not prime 
        prime[0] = false
        prime[1] = false
      
        for (int p = 2; p * p <= p_size; p++) 
        
      
            // If prime[p] is not changed, 
            // then it is a prime 
            if (prime[p]) 
            
      
                // Update all multiples of p, 
                // set them to non-prime 
                for (int i = p * 2; 
                         i <= p_size; i += p) 
                    prime[i] = false
            
        
    
      
    // Function to return the xor of elements 
    // in an array having prime frequency 
    static int xorOfElements(int []arr, int n) 
    
        int i, j; 
        bool []prime = new bool[n + 1];
        for(i = 0; i< n + 1; i++)
            prime[i] = true;
      
        SieveOfEratosthenes(prime, n + 1); 
      
        // Map is used to store 
        // element frequencies 
        Dictionary<int
                   int> m = new Dictionary<int,
                                           int>(); 
        for (i = 0; i < n; i++) 
        
            if(m.ContainsKey(arr[i])) 
                m[arr[i]] = m[arr[i]] + 1; 
            else
                m.Add(arr[i], 1); 
        
      
        int xor = 0; 
      
        // Traverse the map 
        foreach(KeyValuePair<int, int> entry in m)
        
            int key = entry.Key; 
            int value = entry.Value; 
              
            // xor the elements 
            // having prime frequencies 
            if (prime[value]) 
            
                xor ^= (key); 
            
        
        return xor; 
    
      
    // Driver code 
    public static void Main(String []args) 
    
        int []arr = { 5, 4, 6, 5, 4, 6 }; 
        int n = arr.Length; 
      
        Console.WriteLine(xorOfElements(arr, n)); 
    
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

7


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.