Given a value K which is the XOR of all the values from 1 to N, the task is to find the minimum value of N such that XOR from 1 to N is equal to K.
Input: K = 7 Output: 6 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 = 7 Input: K = 10 Output: Not Possible
Approach: This problem is similar to the Calculate XOR from 1 to n. Below are the conditions to be checked:
- If k = 0, then N = 3.
- If k = 1, then N = 1.
- If k % 4 = 0, then N = k.
- If k % 4 = 3, then N = k-1.
Below is the implementation of above approach:
How does this work?
When we do XOR of numbers, we get 0 as XOR value just before a multiple of 4. This keeps repeating before every multiple of 4.
Number Binary-Repr XOR-from-1-to-n 1 1  2 10  3 11  <----- We get a 0 4 100  <----- Equals to n 5 101  6 110  7 111  <----- We get 0 8 1000  <----- Equals to n 9 1001  10 1010  11 1011  <------ We get 0 12 1100  <------ Equals to n
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count minimum bits to flip such that XOR of A and B equal to C
- Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
- Choose X such that (A xor X) + (B xor X) is minimized
- Minimum value of K such that sum of cubes of first K natural number is greater than equal to N
- Count subarrays with sum equal to its XOR value
- Largest possible value of M not exceeding N having equal Bitwise OR and XOR between them
- Number of subarrays such that XOR of one half is equal to the other
- Largest number M having bit count of N such that difference between their OR and XOR value is maximized
- Minimum flips in two binary arrays so that their XOR is equal to another array
- Minimum Bitwise XOR operations to make any two array elements equal
- Minimum insertions to make XOR of an Array equal to half of its sum
- Minimum XOR Value Pair
- Find the node whose xor with x gives minimum value
- Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity
- Find a number such that maximum in array is minimum possible after XOR
- Find XOR of two number without using XOR operator
- Given a set, find XOR of the XOR's of all subsets.
- Possible values of Q such that, for any value of R, their product is equal to X times their sum
- Minimum value of X to make all array elements equal by either decreasing or increasing by X
- Minimum increments by index value required to obtain at least two equal Array elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.