XOR of all the elements in the given range [ L , R ] | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; long computeXOR ( const int n ) { switch ( n & 3 ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } } int main ( ) { int l = 1 , r = 4 ; cout << ( computeXOR ( r ) ^ computeXOR ( l - 1 ) ) ; return 0 ; }