- Related Questions & Answers
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- Find smallest number n such that n XOR n+1 equals to given k in C++
- C Program to print numbers from 1 to N without using semicolon
- Program to find duplicate element from n+1 numbers ranging from 1 to n in Python
- Find count of Almost Prime numbers from 1 to N in C++
- Maximum XOR of Two Numbers in an Array in C++
- Print prime numbers from 1 to N in reverse order
- Find maximum operations to reduce N to 1 in C++
- Count numbers whose difference with N is equal to XOR with N in C++
- Count numbers whose XOR with N is equal to OR with N in C++
- Find all combinations of k-bit numbers with n bits set where 1 <= n <= k in sorted order in C++
- Compute sum of digits in all numbers from 1 to n
- An Interesting Method to Generate Binary Numbers from 1 to n?
- Program to find all missing numbers from 1 to N in Python
- Program to count how many numbers should be appended to create all numbers from 1 to k in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given two positive integers n and k. Our task is to find maximum xor between 1 to n using maximum X numbers

Let’s take an example to understand the problem,

**Input** − n = 5, k = 2

**Output** − 7

**Explanation** −

elements till 5 is 1, 2, 3, 4, 5 Selecting all XOR pairs: 1^2 = 3, 1^3 = 2, 1^4 = 5, 1^5 = 4 2^3 = 4, 2^4 = 6, 2^5 = 7 3^4 = 7, 3^5 = 6 4^5 = 1 The maximum here is 7.

To solve this problem, the maximum XOR can be found for any combination of numbers is found when all the bits of the number are set.

So, if the number is 5 its binary is 101, the maximum XOR will be 111 i.e. 7.

But if the number of elements to be taken for maximum XOR is 1 then the max XOR is 1. Else the maximum XOR will be found by making all bits set.

Program to illustrate the working of our solution,

#include <iostream> using namespace std; int maxXor(int n, int k) { if (k == 1) return n; int result = 1; while (result <= n) result <<= 1; return result - 1; } int main() { int n = 5, k = 2; cout<<"The maximum XOR of "<<k<<" numbers from 1 to"<<n<<" is "<<maxXor(n, k); return 0; }

The maximum XOR of 2 numbers from 1 to 5 is 7

Advertisements