Count ways to represent N as XOR of distinct integers not exceeding N
Last Updated :
01 Jul, 2021
Given a positive integer N, the task is to find the number of ways to represent N as Bitwise XOR of distinct positive integers less than or equal to N.
Examples:
Input: N = 5
Output: 4
Explanation: The given number N(= 5) can be represented as:
- 5 = 5
- 5 = (4 ^ 1)
- 5 = (5 ^ 3 ^ 2 ^ 1)
- 5 = (4 ^ 3 ^ 2)
Therefore, the total count is 4.
Input: N = 6
Output: 8
Naive Approach: The simplest approach to solve the problem is to find all subsets of first N natural numbers and count those subsets having Bitwise XOR value N. After checking for all the subsets, print the total value of the count obtained.
Time Complexity: O(N * 2N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using the observation that the number of ways to represent N as the Bitwise XOR of distinct positive integers is given by .
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void countXorPartition( int N)
{
double a = pow (2, floor (N - log (N + 1) /
log (2)));
cout << a;
}
int main()
{
int N = 5;
countXorPartition(N);
}
|
Java
import java.io.*;
class GFG{
static void countXorPartition( int N)
{
double a = Math.pow( 2 , ( int )(N - Math.log(N + 1 ) /
Math.log( 2 )));
System.out.print(a);
}
public static void main(String[] args)
{
int N = 5 ;
countXorPartition(N);
}
}
|
Python
from math import *
def countXorPartition(N):
a = 2 * * floor(N - log(N + 1 ) / log( 2 ))
print ( int (a))
N = 5
countXorPartition(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void countXorPartition( int N)
{
double a = Math.Pow(2, ( int )(N - Math.Log(N + 1) /
Math.Log(2)));
Console.Write(a);
}
public static void Main()
{
int N = 5;
countXorPartition(N);
}
}
|
Javascript
<script>
function countXorPartition(N)
{
let a = Math.pow(2, Math.floor(N - Math.log(N + 1) /
Math.log(2)));
document.write(a);
}
let N = 5;
countXorPartition(N);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...