XOR of all even numbers from a given range | C ++ Implementation of the above approach ; Function to calculate XOR of numbers in the range [ 1 , n ] ; If n is divisible by 4 ; If n mod 4 is equal to 1 ; If n mod 4 is equal to 2 ; Function to find XOR of even numbers in the range [ l , r ] ; Stores XOR of even numbers in the range [ 1 , l - 1 ] ; Stores XOR of even numbers in the range [ 1 , r ] ; Update xor_r ; Update xor_l ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bitwiseXorRange ( int n ) { if ( n % 4 == 0 ) return n ; if ( n % 4 == 1 ) return 1 ; if ( n % 4 == 2 ) return n + 1 ; return 0 ; } int evenXorRange ( int l , int r ) { int xor_l ; int xor_r ; xor_r = 2 * bitwiseXorRange ( r / 2 ) ; xor_l = 2 * bitwiseXorRange ( ( l - 1 ) / 2 ) ; return xor_l ^ xor_r ; } int main ( ) { int l = 10 ; int r = 20 ; cout << evenXorRange ( l , r ) ; return 0 ; }