Absolute difference between the XOR of Non | Java implementation of the approach ; Function to return max_element from an array ; Function to find the absolute difference between the XOR of non - primes and the XOR of primes in the given array ; Find maximum value in the array ; 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 . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the XOR of primes in X1 and the XOR of non primes in X2 ; The number is prime ; The number is non - prime ; Return the absolute difference ; Driver Code ; Find the absolute difference
import java . util . Arrays ; class GFG { static int max_element ( int [ ] arr ) { int max = arr [ 0 ] ; for ( int ele : arr ) if ( max < ele ) max = ele ; return max ; } static int calculateDifference ( int [ ] arr , int n ) { int max_val = max_element ( arr ) ; boolean [ ] prime = new boolean [ max_val + 1 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int x1 = 1 , x2 = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) x1 ^= arr [ i ] ; else if ( arr [ i ] != 1 ) x2 ^= arr [ i ] ; } return Math . abs ( x1 - x2 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 5 , 10 , 15 , 7 } ; int n = arr . length ; System . out . println ( calculateDifference ( arr , n ) ) ; } }