XOR of all the elements in the given range [ L , R ] | Java implementation of the approach ; Function to return the required XOR ; Modulus operator are expensive on most of the computers . n & 3 will be equivalent to n % 4 n % 4 ; If n is a multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Driver code
class GFG { static long computeXOR ( int n ) { int x = n & 3 ; switch ( x ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } return 0 ; } public static void main ( String args [ ] ) { int l = 1 , r = 4 ; System . out . println ( computeXOR ( r ) ^ computeXOR ( l - 1 ) ) ; } }