Given two integers L and R, the task is to calculate Bitwise XOR of all even numbers in the range [L, R].
Examples:
Example:
Input: L = 10, R = 20
Output: 30
Explanation:
Bitwise XOR = 10 ^ 12 ^ 14 ^ 16 ^ 18 ^ 20 = 30
Therefore, the required output is 30.
Example:
Input: L = 15, R = 23
Output: 0
Explanation:
Bitwise XOR = 16 ^ 18 ^ 20 ^ 22 = 0
Therefore, the required output is 0.
Naive Approach:The simplest approach to solve the problem is to traverse all even numbers in the range [L, R] and print the Bitwise XOR of all the even numbers.
Time Complexity: O(R – L)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
If N is an even number:
2 ^ 4 … ^ (N) = 2 * (1 ^ 2 ^ … ^ (N / 2))
If N is an odd number:
2 ^ 4 … ^ (N) = 2 * (1 ^ 2 ^ … ^ ((N – 1) / 2))
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
class GFG
{
static 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 ;
}
static 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;
}
public static void main (String[] args)
{
int l = 10 ;
int r = 20 ;
System.out.print(evenXorRange(l, r));
}
}
|
Python3
def bitwiseXorRange(n):
if (n % 4 = = 0 ):
return n
if (n % 4 = = 1 ):
return 1
if (n % 4 = = 2 ):
return n + 1
return 0
def evenXorRange(l, r):
xor_r = 2 * bitwiseXorRange(r / / 2 )
xor_l = 2 * bitwiseXorRange((l - 1 ) / / 2 )
return xor_l ^ xor_r
if __name__ = = '__main__' :
l = 10
r = 20
print (evenXorRange(l, r))
|
C#
using System;
class GFG {
static 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;
}
static 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;
}
static void Main()
{
int l = 10;
int r = 20;
Console.Write(evenXorRange(l, r));
}
}
|
Javascript
<script>
function bitwiseXorRange(n)
{
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
function evenXorRange(l, r)
{
let xor_l;
let xor_r;
xor_r
= 2 * bitwiseXorRange(Math.floor(r / 2));
xor_l
= 2 * bitwiseXorRange(Math.floor((l - 1) / 2));
return xor_l ^ xor_r;
}
let l = 10;
let r = 20;
document.write(evenXorRange(l, r));
</script>
|
Time Complexity: O(1).
Auxiliary Space: O(1)