Discover all M in vary [2, N] such that bitwise OR until M is the same as the worth until M-1

[ad_1]

Given an integer N, the duty is to search out all attainable integer M within the vary [2, N] such that the bitwise OR of all constructive values until M is similar because the bitwise OR of all constructive values until M-1.

Examples:

Enter: N = 4
Output: 1
Rationalization: Bitwise OR until 3 = 1 | 2 | 3 = 3.
Bitwse OR until 2 = 1 | 2 = 3.

Enter: N = 7
Output: 4

 

Method: The method to unravel this drawback relies on the next remark:

Contemplate p(x) to the bitwise OR until x. So p(x) = 1 | 2 | 3 | . . . | (x-1) | x
Given p(x) = 1 | 2 | 3 | . . . | x – 1 | x. Subsequently, p(x + 1) can be totally different from p(x) if there’s a new “1” bit in (x + 1) that isn’t current within the binary sequence of p(x).

Now, allow us to observe the sample:

Decimal Quantity Binary Quantity
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001

We will see {that a} new “1” bit that hasn’t beforehand appeared within the vary [1, x] seems at each energy of two.
As such,  p(x) = 1 | 2 | 3 | . . . | x – 1 | x 
                     = 2a+1 – 1, the place a = log2x. 
This suggests that, for a given a, there can be ( 2a + 1 – 2a – 1 ) values of x the place p(x) = p(x – 1).

Comply with the step beneath to unravel this drawback:

  • Calculate a = log2N. 
  • Iterate via the powers (say utilizing variable exp) of two from 1 to a and increment ans (initially 0) by ( 2 exp + 1 – 2exp – 1 ).
  • Lastly, depend for the pairs between N and 2a by including (n – 2a) to ans.

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int checkXORrange(int n)

{

    int ans = 0;

    int a = log2(n);

  

    for (int exp = 1; exp <= a; exp++)

        ans += pow(2, exp) - pow(2, exp - 1) - 1;

  

    ans += n - pow(2, a);

    return ans;

}

  

int principal()

{

    int N = 7;

  

    

    cout << checkXORrange(N) << endl;

    return 0;

}

C

  

#embrace <math.h>

#embrace <stdio.h>

  

int checkXORrange(int n)

{

    int ans = 0;

    int a = log2(n);

    for (int exp = 1; exp <= a; exp++)

        ans += pow(2, exp) - pow(2, exp - 1) - 1;

    ans += n - pow(2, a);

    return ans;

}

  

int principal()

{

    int N = 7;

  

    

    printf("%dn", checkXORrange(N));

    return 0;

}

Python3

  

import math

  

def checkXORrange(n):

    ans = 0

    a = int(math.log2(n))

    for exp in vary(1, a + 1):

        ans += 2 ** exp - 2 ** (exp - 1) - 1

    ans += n - 2 ** a

    return ans

  

if __name__ == "__main__":

    N = 7

    print(checkXORrange(N))

Time Complexity: O(log2N)
Auxiliary Area: O(1)

[ad_2]

Leave a Reply