Kaosar and Count ORz#12436

Kaosar and Count ORz (Editorial)

Problem Author:

Al_Kaosar

Prepared by:

MathModel

Edited by:

MathModel

Solution

For the bitwise OR condition x \ | \ y = n to hold, we must consider each bit position independently. Let n_i, x_i, and y_i be the -th bits of and respectively.

  • If n_i = 0: The only possibility is x_i = 0 and y_i = 0. (1 choice)

  • If n_i = 1: The pair (x_i, y_i) can be (0, 1), (1, 0), or . (3 choices)

Let be the number of set bits (population count) in . The total number of pairs such that 0 \le x, y \le n and x \ | \ y = n is exactly 3^k. Note that the constraint x, y \le n is naturally satisfied because and are submasks of .

The problem requires 1 \le x, y \le n. Therefore, we must exclude cases where x=0 or y=0:

  1. If x=0, then 0 \ | \ y = n \implies y = n. This gives the pair .

  2. If y=0, then x \ | \ 0 = n \implies x = n. This gives the pair .

Since n \ge 1 in all test cases, these two pairs are distinct. Thus, we subtract 2 from our total count. The final answer is (3^k - 2) \pmod{10^9+7}.

The complexity per test case is O(\log n) due to modular exponentiation.

for _ in range(int(input())):
    n=int(input())
    k=n.bit_count()
    mod=10**9+7
    print((pow(3,k,mod)-2)%mod)