抑或和
计算 $1 \oplus 2 \oplus 3 \oplus4 \oplus \cdots \oplus n $
-
\([2^k,2^{k+1}-1]\) 除了\(2^k(k\geq 1)\)最高位之外,每一个数都能在\([0,2^k-1]\)上找到数与它对应,使得\(\forall x_1 \in [2^k,2^{k+1}-1]\) , $\exists x_2=x_1-2^k \(,使得\)x_1 \oplus x_2 = 2^k$,而总共可以找到\(2^k\)个数,所以就可以推出:
\[1 \oplus 2 \oplus 3 \oplus4 \oplus \cdots \oplus (2^k-1) =0 \ \ (k\geq 1) \] -
以此类推,若\(x=2^{k_1}+2^{k_2},(k_1 \geq 1 ,k_2 \geq 1)\) , 首先\(1 \oplus 2 \oplus 3 \oplus4 \oplus \cdots \oplus (2^{k_1}-1) =0\) , 对于\([2^{k_1},2^{k_1}+2^{k_2}]\) 该区间,由于在\(k_1\)位上出现了\(2^{k_2}\)次,令\(f(x,y)=x\oplus(x+1)\oplus(x+2)\oplus \cdots \oplus y \ \ (x\leq y)\)也就有\(f(2^{k_1},2^{k_1}+2^{k_2})=f(0,2^{k_2})=0\)
-
因此可以推出:
\[f(0,x)= \left \{{ \begin{array}{} x, \ \ \ \ \ x \%4 =0 \\ 1, \ \ \ \ \ x \%4 =1 \\ x+1, \ \ \ \ \ x \%4 =2 \\ 0, \ \ \ \ \ x \%4 =3 \\ \end{array} } \right. \]
\(f(0,x)\) 函数代码:
i64 f(i64 x)
{
i64 ans=0;
for(int i=0;i<=x%4;i++)
{
ans^=x-i;
}
return ans;
}
或者:
i64 f(i64 x)
{
i64 t=x%4;
if(t==0)return x;
else if(t==1)return 1;
else if(t==2)return x+1;
return 0;
}
任何时候都有比放弃更好的选择。

浙公网安备 33010602011771号