Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array

Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.

Examples:

Input: arr[] = {1, 3, 5, 10, 15, 7}
Output: 4
Xor of non-primes = 10 ^ 15 = 5
Xor of primes = 3 ^ 5 ^ 7 = 1
|5 – 1| = 4



Input: arr[] = {3, 4, 6, 7}
Output: 2

Naive approach: A simple solution is to traverse the array and keep checking for every element if it is prime or not. If number is prime, then XOR it to X1 which represents the XOR of primes else XOR it to X2 which represents the XOR of non-primes. After traversing the whole array, take the absolute difference between X1 and X2.

Efficient approach: Generate all primes up to the maximum element of the array using the Sieve of Eratosthenes. Now, traverse the array and check whether the current element is prime or not. If the element is prime then XOR it with X1 else XOR it with X2. Final print abs(X1 – X2).

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 find the absolute difference
// between the XOR of non-primes and the
// XOR of primes in the given array
int calculateDifference(int arr[], int n)
{
  
    // Find maximum value in the array
    int max_val = *max_element(arr, arr + n);
  
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    vector<bool> prime(max_val + 1, true);
  
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; p++) {
  
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
  
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime[i] = false;
        }
    }
  
    // Store the XOR of primes in X1 and
    // the XOR of non primes in X2
    int X1 = 1, X2 = 1;
    for (int i = 0; i < n; i++) {
  
        if (prime[arr[i]]) {
  
            // The number is prime
            X1 ^= arr[i];
        }
        else if (arr[i] != 1) {
  
            // The number is non-prime
            X2 ^= arr[i];
        }
    }
  
    // Return the absolute difference
    return abs(X1 - X2);
}
  
// Driver code
int main()
{
    int arr[] = { 1, 3, 5, 10, 15, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Find the absolute difference
    cout << calculateDifference(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
import java.util.Arrays;
  
class GFG
{
  
    // Function to return 
    // max_element from an array
    static int max_element(int[] arr) 
    {
        int max = arr[0];
  
        for (int ele : arr)
            if (max < ele)
                max = ele;
  
        return max;
    }
  
    // Function to find the absolute difference
    // between the XOR of non-primes and the
    // XOR of primes in the given array
    static int calculateDifference(int[] arr, int n) 
    {
  
        // Find maximum value in the array
        int max_val = max_element(arr);
  
        // USE SIEVE TO FIND ALL PRIME NUMBERS 
        // LESS THAN OR EQUAL TO max_val
        // Create a boolean array "prime[0..n]". 
        // A value in prime[i] will finally be false
        // if i is Not a prime, else true.
        boolean[] prime = new boolean[max_val + 1];
        Arrays.fill(prime, true);
  
        // Remaining part of SIEVE
        prime[0] = false;
        prime[1] = false;
        for (int p = 2; p * p <= max_val; p++) 
        {
  
            // If prime[p] is not changed, 
            // then it is a prime
            if (prime[p] == true
            {
  
                // Update all multiples of p
                for (int i = p * 2
                         i <= max_val; i += p)
                    prime[i] = false;
            }
        }
  
        // Store the XOR of primes in X1 and
        // the XOR of non primes in X2
        int x1 = 1, x2 = 1;
        for (int i = 0; i < n; i++) 
        {
            if (prime[arr[i]])
  
                // The number is prime
                x1 ^= arr[i];
            else if (arr[i] != 1)
  
                // The number is non-prime
                x2 ^= arr[i];
        }
  
        // Return the absolute difference
        return Math.abs(x1 - x2);
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        int[] arr = { 1, 3, 5, 10, 15, 7 };
        int n = arr.length;
  
        // Find the absolute difference
        System.out.println(calculateDifference(arr, n));
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to find the absolute difference
# between the XOR of non-primes and the
# XOR of primes in the given array
def calculateDifference(arr, n):
  
    # Find maximum value in the array
    max_val = max(arr)
  
    # USE SIEVE TO FIND ALL PRIME NUMBERS 
    # LESS THAN OR EQUAL TO max_val
    # Create a boolean array "prime[0..n]". 
    # A value in prime[i] will finally be 
    # false if i is Not a prime, else true.
    prime = [True for i in range(max_val + 1)]
  
    # Remaining part of SIEVE
    prime[0] = False
    prime[1] = False
    for p in range(2, max_val + 1):
  
        if p * p > max_val + 1:
            break
  
        # If prime[p] is not changed, 
        # then it is a prime
        if (prime[p] == True):
  
            # Update all multiples of p
            for i in range(2 * p, max_val + 1, p):
                prime[i] = False
  
    # Store the XOR of primes in X1 and
    # the XOR of non primes in X2
    X1 = 1
    X2 = 1
    for i in range(n):
  
        if (prime[arr[i]]):
  
            # The number is prime
            X1 ^= arr[i]
  
        elif (arr[i] != 1):
  
            # The number is non-prime
            X2 ^= arr[i]
  
    # Return the absolute difference
    return abs(X1 - X2)
  
# Driver code
arr = [1, 3, 5, 10, 15, 7]
n = len(arr)
  
# Find the absolute difference
print(calculateDifference(arr, n))
  
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
      
class GFG
{
  
    // Function to return 
    // max_element from an array
    static int max_element(int[] arr) 
    {
        int max = arr[0];
  
        foreach (int ele in arr)
            if (max < ele)
                max = ele;
  
        return max;
    }
  
    // Function to find the absolute difference
    // between the XOR of non-primes and the
    // XOR of primes in the given array
    static int calculateDifference(int[] arr, int n) 
    {
  
        // Find maximum value in the array
        int max_val = max_element(arr);
  
        // USE SIEVE TO FIND ALL PRIME NUMBERS 
        // LESS THAN OR EQUAL TO max_val
        // Create a boolean array "prime[0..n]". 
        // A value in prime[i] will finally be false
        // if i is Not a prime, else true.
        bool[] prime = new bool[max_val + 1];
        for(int index = 0; index < max_val + 1; index++)
            prime[index] = true;
  
        // Remaining part of SIEVE
        prime[0] = false;
        prime[1] = false;
        for (int p = 2; p * p <= max_val; p++) 
        {
  
            // If prime[p] is not changed, 
            // then it is a prime
            if (prime[p] == true
            {
  
                // Update all multiples of p
                for (int i = p * 2; 
                        i <= max_val; i += p)
                    prime[i] = false;
            }
        }
  
        // Store the XOR of primes in X1 and
        // the XOR of non primes in X2
        int x1 = 1, x2 = 1;
        for (int i = 0; i < n; i++) 
        {
            if (prime[arr[i]])
  
                // The number is prime
                x1 ^= arr[i];
            else if (arr[i] != 1)
  
                // The number is non-prime
                x2 ^= arr[i];
        }
  
        // Return the absolute difference
        return Math.Abs(x1 - x2);
    }
  
    // Driver Code
    public static void Main(String[] args) 
    {
        int[] arr = { 1, 3, 5, 10, 15, 7 };
        int n = arr.Length;
  
        // Find the absolute difference
        Console.WriteLine(calculateDifference(arr, n));
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

4


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.