Given two integers L and R, the task is to find the XOR of elements of the range [L, R].
Input: L = 4, R = 8
4 ^ 5 ^ 6 ^ 7 ^ 8 = 8
Input: L = 3, R = 7
Naive Approach: Intilialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time.
Efficient Approach: By following the approach discussed here, we can find the XOR of elements from the range [1, N] in O(1) time.
Using this approach, we have to find xor of elements from the range [1, L – 1] and from the range [1, R] and then xor the respective answers again to get the xor of the elements from the range [L, R]. This is because every element from the range [1, L – 1] will get XORed twice in the result resulting in a 0 which when XORed with the elements of the range [L, R] will give the result.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find numbers with K odd divisors in a given range
- Find numbers with n-divisors in a given range
- Find a range of composite numbers of given length
- Find the number of divisors of all numbers in the range [1, n]
- Find the count of distinct numbers in a range
- Find all the possible numbers in a range that can be evenly divided by its digits
- Find kth smallest number in range [1, n] when all the odd numbers are deleted
- Find the highest occurring digit in prime numbers in a range
- Program to find count of numbers having odd number of divisors in given range
- Sum of all even numbers in range L and R
- Sum of all odd natural numbers in range L and R
- Sum of Fibonacci Numbers in a range
- Sum of all the prime numbers in a given range
- Prime numbers in a given range using STL | Set 2
- Sum of all natural numbers in range L to R
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.