Maximum XOR using K numbers from 1 to n in C++

C++Server Side ProgrammingProgramming

Problem statement

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

If n = 7 and k = 3 then output will be 7

We can select 1, 2, 4 for maximum XOR-value

Algorithm

1. for a given n and k >1 the maximum possible XOR value is 2log2(n)+1 - 1

Example

#include <bits/stdc++.h>
using namespace std;
int maxXOR(int n, int k){
   int c = log2(n) + 1;
   return ((1 << c) - 1);
}
int main(){
   int n = 7;
   int k = 3;
   cout << "Result = " << maxXOR(n, k) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Result = 7
raja
Published on 10-Feb-2020 09:56:44
Advertisements