
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum XOR using K numbers from 1 to n in C++
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.
Example
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; }
Output
The maximum XOR of 2 numbers from 1 to 5 is 7
- Related Articles
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n 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
- Maximum XOR of Two Numbers in an Array in C++
- Program to find maximum sum by removing K numbers from ends in python
- Print prime numbers from 1 to N in reverse order
- 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 Maximum XOR value of a sub-array of size k in C++
- Program to find maximum XOR with an element from array in Python
- Compute sum of digits in all numbers from 1 to n
- Java program to swap two numbers using XOR operator
- Program to find all missing numbers from 1 to N in Python
- How to Display all Prime Numbers from 1 to N in Golang?

Advertisements