Maximum XOR using K numbers from 1 to n
Last Updated :
15 Feb, 2023
Given a positive integer n and k. Find maximum xor of 1 to n using at most k numbers. Xor sum of 1 to n is defined as 1 ^ 2 ^ 3 ^ … ^ n.
Examples :
Input : n = 4, k = 3
Output : 7
Explanation
Maximum possible xor sum is 1 ^ 2 ^ 4 = 7.
Input : n = 11, k = 1
Output : 11
Explanation
Maximum Possible xor sum is 11.
If we have k = 1 then the maximum possible xor sum is ‘n’ itself. Now for k > 1, we can always have a number with its all bits set till the most significant set bit in ‘n’.
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll maxXorSum(ll n, ll k)
{
if (k == 1)
return n;
ll res = 1;
while (res <= n)
res <<= 1;
return res - 1;
}
int main()
{
ll n = 4, k = 3;
cout << maxXorSum(n, k);
return 0;
}
|
Java
public class Main {
static int maxXorSum( int n, int k)
{
if (k == 1 )
return n;
int res = 1 ;
while (res <= n)
res <<= 1 ;
return res - 1 ;
}
public static void main(String[] args)
{
int n = 4 , k = 3 ;
System.out.print(maxXorSum(n, k));
}
}
|
Python
def maxXorSum( n , k ):
if k = = 1 :
return n
res = 1
while res < = n:
res << = 1
return res - 1
n = 4
k = 3
print ( maxXorSum(n, k) )
|
C#
using System;
public class main {
static int maxXorSum( int n, int k)
{
if (k == 1)
return n;
int res = 1;
while (res <= n)
res <<= 1;
return res - 1;
}
public static void Main()
{
int n = 4, k = 3;
Console.WriteLine(maxXorSum(n, k));
}
}
|
PHP
<?php
function maxXorSum( $n , $k )
{
if ( $k == 1)
return $n ;
$res = 1;
while ( $res <= $n )
$res <<= 1;
return $res - 1;
}
$n = 4;
$k = 3;
echo maxXorSum( $n , $k );
?>
|
Javascript
<script>
function maxXorSum(n, k)
{
if (k == 1)
return n;
let res = 1;
while (res <= n)
res <<= 1;
return res - 1;
}
let n = 4, k = 3;
document.write(maxXorSum(n, k));
</script>
|
Time Complexity : O(logn)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...