C - Mod of XOR 解説 by evima
Let \(k\) be the topbit of \(C\). That is, define non-negative integer \(k\) such that \(2^k \le C < 2^{k+1}\).
1. When \(2^k \le n < 2^{k+1}\)
Since both \(n\) and \(C\) have topbit \(k\), we have \(n \oplus C < n\), so \(X=(n \oplus C) \bmod n = n \oplus C\). Therefore, if a solution exists in this range, the solution is \(n=C\oplus X\).
2. When \(n < 2^k\)
Since \(X=(n \oplus C) \bmod n< n < 2^k\), if a solution exists in this range, \(n=C \oplus X\) is also a solution.
3. When \(2^{k+1} \le n\)
Let \(n_1\) and \(n_2\) be the quotient and remainder when \(n\) is divided by \(2^{k+1}\), respectively (\(n=n_12^{k+1}+n_2\)).
3 - A. When \(n_2 < 2^k\)
The topbit of \(C\) becomes \(0\) in \(n\), so \(n \oplus C > n\) holds. From this and \(n\oplus C \le n + C < 2n\), we have \(\displaystyle \left\lfloor\frac{n\oplus C}{n} \right\rfloor = 1\), so \(X=(n \oplus C) \bmod n = (n \oplus C) - n = C - 2(C \ \mathrm{AND}\ n)\).
Therefore, if a solution exists in this range, \(\displaystyle n=2^{50}+\frac{C-X}2\) is also one solution.
3 - B. When \(2^k \le n_2 < 2^{k+1}\)
By the same argument as in 1., if a solution exists in this range, the solution is \(n=C\oplus X\).
From the above discussion, we just need to check whether the two values \(\displaystyle n = C\oplus X,\ 2^{50}+\frac{C-X}2\) actually satisfy the equation.
By implementing the above appropriately, we can solve this problem. The time complexity is \(O(1)\) per test case.
Implementation Example (Python3)
for _ in range(int(input())):
c, x = map(int, input().split())
ans = -1
for n in (c ^ x, 2**50 + (c - x) // 2):
if n > 0 and (n ^ c) % n == x:
ans = n
print(ans)
投稿日時:
最終更新: