Maximum set of number from the first N natural numbers whose Bitwise AND is positive
Last Updated :
19 Aug, 2022
Given a positive integer N, the task is to find the maximum set of numbers from the first N natural numbers whose Bitwise AND is positive
Examples:
Input: N = 7
Output: 4
Explanation:
The set of numbers from the first N(= 7) natural numbers whose Bitwise AND is positive is {4, 5, 6, 7}, which is of maximum length.
Input: N = 16
Output: 8
Approach: The given problem can be solved based on the observation that 2N and (2N – 1), results in 0. Therefore, the maximum length of the set must not include both 2N and (2N – 1) in the same set. The maximum subarray with non-zero AND value can be found out as:
- Find the maximum power of 2 less than or equal to N and if N is a power of 2, the answer should be N/2, for example, when N is 16, the maximum subarray with non-zero AND value is 8.
- Otherwise, the answer is the length between the N and the largest power of 2 less than or equal to N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maximumSizeOfSet( int N)
{
if (N == 1)
return 1;
int temp = 1;
while (temp * 2 <= N) {
temp *= 2;
}
if (N & (N - 1) == 0)
return N / 2;
else
return N - temp + 1;
}
int main()
{
int N = 7;
cout << maximumSizeOfSet(N);
return 0;
}
|
Java
class GFG{
public static int maximumSizeOfSet( int N)
{
if (N == 1 )
return 1 ;
int temp = 1 ;
while (temp * 2 <= N) {
temp *= 2 ;
}
if ((N & (N - 1 )) == 0 )
return N / 2 ;
else
return N - temp + 1 ;
}
public static void main(String args[])
{
int N = 7 ;
System.out.println(maximumSizeOfSet(N));
}
}
|
Python3
def maximumSizeOfSet(N):
if (N = = 1 ):
return 1
temp = 1
while (temp * 2 < = N):
temp * = 2
if (N & (N - 1 ) = = 0 ):
return N / / 2
else :
return N - temp + 1
if __name__ = = "__main__" :
N = 7
print (maximumSizeOfSet(N))
|
C#
using System;
public class GFG {
static int maximumSizeOfSet( int N)
{
if (N == 1)
return 1;
int temp = 1;
while (temp * 2 <= N) {
temp *= 2;
}
if ((N & (N - 1)) == 0)
return N / 2;
else
return N - temp + 1;
}
public static void Main(String[] args)
{
int N = 7;
Console.WriteLine(maximumSizeOfSet(N));
}
}
|
Javascript
<script>
const maximumSizeOfSet = (N) => {
if (N == 1)
return 1;
let temp = 1;
while (temp * 2 <= N) {
temp *= 2;
}
if (N & (N - 1) == 0)
return parseInt(N / 2);
else
return N - temp + 1;
}
let N = 7;
document.write(maximumSizeOfSet(N));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...