The Wayback Machine - https://web.archive.org/web/20220105223313/https://www.geeksforgeeks.org/find-longest-range-from-numbers-in-range-1-n-having-positive-bitwise-and/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find longest range from numbers in range [1, N] having positive bitwise AND

  • Last Updated : 05 Jan, 2022

Given a number N, the task is to find the longest range of integers [L, R] such that 1 ≤ L ≤ R ≤ N and the bitwise AND of all the numbers in that range is positive.

Examples:

Resolution Days 2022 GeeksforGeeks

Input: N = 7
Output: 4 7
Explanation: Check and from 1 to 7
Bitwise AND operations:
from 1 to 7 is 0 
from 2 to 7 is 0
from 3 to 7 is 0
from 4 to 7 is 4
Therefore, maximum range comes out from L = 4 to R = 7. 

Input: K = 16
Output: 8 15



 

Approach: The problem can be solved based on the following mathematical observation. If 2K is the closest exponent of 2 greater than N then the maximum range will be either of the two:

  • From 2(K – 2) to (2(K – 1) – 1) [both value inclusive] or,
  • From 2(K – 1) to N

Because these ranges confirm that all the numbers in the range will have the most significant bit set for all of them. If the ranges vary for powers of 2 then the bitwise AND of the range will become 0.

Below is the implementation of the above approach.

C++




// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the closest exponent of 2
// which is greater than K
int minpoweroftwo(int K)
{
    int count = 0;
    while (K > 0) {
        count++;
        K = K >> 1;
    }
    return count;
}
  
// Function to find the longest range
void findlongestrange(int N)
{
  
    int K = minpoweroftwo(N);
    int y = N + 1 - pow(2, K - 1);
    int z = (pow(2, K - 1) - pow(2, K - 2));
  
    if (y >= z) {
        cout << pow(2, K - 1) << " " << N;
    }
    else {
        cout << pow(2, K - 2) << " " 
            << pow(2, K - 1) - 1;
    }
}
  
// Driver code
int main()
{
    int N = 16;
    findlongestrange(N);
    return 0;
}

C




// C code to implement above approach
#include <math.h>
#include <stdio.h>
  
// Function to find the closest exponent of 2 
// which is greater than K
int minpoweroftwo(int K)
{
    int count = 0;
    while (K > 0) {
        count++;
        K = K >> 1;
    }
    return count;
}
  
// Function to find the longest range
void findlongestrange(int N)
{
  
    int K = minpoweroftwo(N);
    int y = N + 1 - pow(2, K - 1);
    int z = (pow(2, K - 1) - pow(2, K - 2));
  
    if (y >= z) {
        printf("%d %d", (int)pow(2, K - 1), N);
    }
    else {
        printf("%d %d", (int)pow(2, K - 2),
               (int)pow(2, K - 1)-1);
    }
}
  
// Driver code
int main()
{
    int N = 16;
    findlongestrange(N);
    return 0;
}
Output
8 15

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!