You are given two positive integer n and k. You have to calculate the maximum possible XOR value of at most k-elements from 1 to n.
Note:k > 1
Input : n = 7, k = 3 Output : 7 Explanation : You can select 1, 2, 4 for maximum XOR-value Input : n = 7, k = 2 Output : 7 Explanation : You can select 3 and 4 for maximum value.
For any value of k we can select atleast two numbers from 1 to n and for the required result we have to take a closer look on the bit-representation of n. So lets understand it through an example. Suppose n = 6 and k = 2:
Bit representation of 6 = 110
Bit representation of 5 = 101
Bit representation of 4 = 100
Bit representation of 3 = 011
Bit representation of 2 = 010
Bit representation of 1 = 001
Now, you can see that after selecting as much numbers you want and selecting any of them you can not obtain XOR value greater than 111 i.e 7. So, for a given n and k >1 the maximum possible XOR value is 2log2(n)+1-1 (that is the value when all bits of n are turned to 1).
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.
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Compute the minimum or maximum of two integers without branching
- Find the maximum subarray XOR in a given array
- Find the maximum subset XOR of a given set
- Maximum XOR value in matrix
- Find Maximum XOR value of a sub-array of size k
- Maximum 0's between two immediate 1's in binary representation
- Maximum XOR value of a pair from a range
- Find maximum XOR of given integer in a stream of integers
- Remove one bit from a binary number to get maximum value
- Maximum possible XOR of every element in an array with another array
- Smallest number whose set bits are maximum in a given range
- Maximum AND value of a pair in an array
- Print pair with maximum AND value in an array
- Maximum XOR using K numbers from 1 to n
- Maximum OR sum of sub-arrays of two different arrays
- Number whose sum of XOR with given array range is maximum
- Maximum steps to transform 0 to X with bitwise AND
- Maximum subset with bitwise OR equal to k
- Find the node whose xor with x gives maximum value
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.