Open In App

Minimum count of consecutive integers till N whose bitwise AND is 0 with N

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N, the task is to print the minimum count of consecutive numbers less than N such that the bitwise AND of these consecutive elements, including integer N, is equal to 0.

Examples:

Input: N = 18
Output: 3
Explanation: 
One possible way is to form a sequence of {15, 16, 17, and 18}. The bitwise AND of the given numbers is equal to 0.
Therefore, a minimum of 3 numbers are needed to make the bitwise AND of a sequence of 4 consecutive elements, including 18 to 0.

Input: N = 4
Output: 1
Explanation: 
One possible way is to form a sequence of {4, 3}. The bitwise AND of the given numbers is equal to 0.
Therefore, a minimum of 1 number is needed to make the bitwise AND of a sequence of 2 consecutive elements including 4 to 0.

Naive Approach: 

1) We start iterating from N till 1 and in each iteration, we check if the bitwise AND of all the numbers so far is equal to 0 or not.

2) To check if the bitwise AND is equal to 0 or not, we use the property that a bitwise AND of two numbers is equal to 0 if and only if the binary representations of the two numbers do not have any common 1’s.

3) So, for each number i, we check if i & (i-1) is equal to 0 or not. If it is, then the bitwise AND of all the numbers so far, including i, is equal to 0.
4) If the bitwise AND is equal to 0, then we return the count of numbers so far plus 1, since we need to include i in the sequence as well.
5) If we reach the end of the loop and have not found a sequence with a bitwise AND equal to 0, then we return the count of numbers so far plus 1.

Implementation of the above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
int minConsecutiveNumbers(int N) {
    int count = 0;
    for(int i=N; i>0; i--) {
        if((i & (i-1)) == 0) {
            return count+1;
        }
        count++;
    }
    return count+1;
}
 
int main() {
    int N = 18;
    cout << minConsecutiveNumbers(N) << endl;
    return 0;
}


Java




public class GFG {
  public static int minConsecutiveNumbers(int N)
  {
    // Initialize a count variable to keep track of the
    // number of integers required to be added to get a
    // power of 2
    int count = 0;
 
    // Iterate over the integers from N down to 1
    for (int i = N; i > 0; i--)
    {
       
      // Check if the integer is a power of 2 by using
      // bitwise AND operator
      if ((i & (i - 1)) == 0)
      {
         
        // If the integer is a power of 2, return
        // the count + 1 because we need to include
        // the power of 2 itself
        return count + 1;
      }
       
      // Increment the count because we have to add
      // this integer to get a power of 2
      count++;
    }
     
    // If we reach here, it means no power of 2 was
    // found in the range, so we return the count + 1
    // for the original number itself
    return count + 1;
  }
 
  public static void main(String[] args)
  {
     
    // Test the function with an example value
    int N = 18;
    System.out.println(minConsecutiveNumbers(N));
  }
}


Python3




def minConsecutiveNumbers(N):
   
    # Initialize a count variable to keep track of the number of integers
    # required to be added to get a power of 2
    count = 0
 
    # Iterate over the integers from N down to 1
    for i in range(N, 0, -1):
       
        # Check if the integer is a power of 2 by using bitwise AND operator
        if (i & (i-1)) == 0:
           
            # If the integer is a power of 2, return the count + 1
            # because we need to include the power of 2 itself
            return count+1
 
        # Increment the count because we have to add this integer to get a power of 2
        count += 1
 
    # If we reach here, it means no power of 2 was found in the range,
    # so we return the count + 1 for the original number itself
    return count+1
 
# Test the function with an example value
N = 18
print(minConsecutiveNumbers(N))


Javascript




// Function to find the minimum number of consecutive numbers
// that can be added to get a number that is a power of 2
function minConsecutiveNumbers(N) {
    let count = 0;
    for(let i=N; i>0; i--) {
        if((i & (i-1)) == 0) { // Check if i is a power of 2
            return count+1;
        }
        count++;
    }
    return count+1;
}
 
let N = 18;
console.log(minConsecutiveNumbers(N)); // Output the result


C#




using System;
 
public class Program {
    public static int MinConsecutiveNumbers(int N)
    {
        int count = 0;
        for (int i = N; i > 0; i--) {
            if ((i & (i - 1)) == 0) {
                return count + 1;
            }
            count++;
        }
        return count + 1;
    }
 
    public static void Main()
    {
        int N = 18;
        Console.WriteLine(MinConsecutiveNumbers(N));
    }
}
// This code is contributed by Prajwal Kandekar


Output: 3

Time Complexity: O(N)
Auxiliary Space: O(1)

Efficient Approach: The given problem can be solved based on the following observations: 

  1. To make the bitwise AND of sequence including N equal to 0, it is necessary to make the MSB bit of the number N equal to 0.
  2. Therefore, the idea is to include all the integers greater than or equal to (2MSB -1) and less than N in the sequence, it will give the minimum count.

Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
int decimalToBinary(int N)
{
  
    // To store the binary number
    int B_Number = 0;
    int cnt = 0;
    while (N != 0)
    {
        int rem = N % 2;
        double c = pow(10, cnt);
        B_Number += rem * c;
        N /= 2;
  
        // Count used to store exponent value
        cnt++;
    }
  
    return B_Number;
}
    // Function to count the minimum count of
    // integers such that bitwise AND of that
    // many consecutive elements is equal to 0
    int count(int N)
    {
 
        // Stores the binary
        // representation of N
        string a = to_string(decimalToBinary(N));
 
        // Stores the MSB bit
        int m = a.size() - 1;
       
        // Stores the count
        // of numbers
        int res = (N - (pow(2, m) - 1));
 
        // Return res
        return res;
 
    }
     
 
// Driver Code
int main() {
 
    // Given Input
    int N = 18;
 
    // Function Call
    cout<< count(N);
return 0;
}
 
// This code is contributed by shikhasingrajput


Java




// Java program for the above approach
class GFG
{
   
    // Function to count the minimum count of
    // integers such that bitwise AND of that
    // many consecutive elements is equal to 0
    static int count(int N)
    {
 
        // Stores the binary
        // representation of N
        String a = Integer.toBinaryString(N);
 
        // Stores the MSB bit
        int m = a.length() - 1;
       
        // Stores the count
        // of numbers
        int res = (int) (N - (Math.pow(2, m) - 1));
 
        // Return res
        return res;
 
    }
 
    // Driver Code
    public static void main(String[] args) {
 
        // Given Input
        int N = 18;
 
        // Function Call
        System.out.println(count(N));
    }
}
 
// This code is contributed by shikhasingrajput


Python3




# Python program for the above approach
 
# Function to count the minimum count of
# integers such that bitwise AND of that
# many consecutive elements is equal to 0
 
 
def count(N):
 
    # Stores the binary
    # representation of N
    a = bin(N)
 
    # Excludes first two
    # characters "0b"
    a = a[2:]
 
    # Stores the MSB bit
    m = len(a)-1
 
    # Stores the count
    # of numbers
    res = N - (2**m-1)
 
    # Return res
    return res
 
 
# Driver Code
# Given Input
N = 18
 
# Function Call
print(count(N))


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
   
    // Function to count the minimum count of
    // integers such that bitwise AND of that
    // many consecutive elements is equal to 0
    static int count(int N)
    {
 
        // Stores the binary
        // representation of N
        String a = Convert.ToString(N, 2);
 
        // Stores the MSB bit
        int m = a.Length - 1;
       
        // Stores the count
        // of numbers
        int res = (int) (N - (Math.Pow(2, m) - 1));
 
        // Return res
        return res;
 
    }
 
    // Driver Code
    public static void Main(String[] args) {
 
        // Given Input
        int N = 18;
 
        // Function Call
        Console.WriteLine(count(N));
    }
}
 
// This code is contributed by umadevi9616


Javascript




<script>
// javascript program for the above approach
 
    // Function to count the minimum count of
    // integers such that bitwise AND of that
    // many consecutive elements is equal to 0
    function count(N)
    {
 
        // Stores the binary
        // representation of N
        var a = N.toString(2);
 
        // Stores the MSB bit
        var m = a.length - 1;
       
        // Stores the count
        // of numbers
        var res = N - (Math.pow(2, m) - 1);
 
        // Return res
        return res;
 
    }
 
    // Driver Code
     
        // Given Input
        var N = 18;
 
        // Function Call
        document.write(count(N));
 
 
// This code is contributed by shikhasingrajput
</script>


Output

3

Time Complexity: O(log(N))
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads