XOR of all the elements in the given range [ L , R ] | 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
< ? php function computeXOR ( $ n ) { $ x = $ n & 3 ; switch ( $ x ) { case 0 : return $ n ; case 1 : return 1 ; case 2 : return $ n + 1 ; case 3 : return 0 ; } return 0 ; } $ l = 1 ; $ r = 4 ; echo ( computeXOR ( $ r ) ^ computeXOR ( $ l - 1 ) ) ; ? >