POJ3495 Bitwise XOR of Arithmetic Progression
Bitwise XOR of Arithmetic Progression
Write a program that, given three positive integers x, y and z (x, y, z < 232, x ≤ y), computes the bitwise exclusive disjunction (XOR) of the arithmetic progression x, x + z, x + 2z, …, x + kz, where k is the largest integer such that x + kz ≤ y.
题解
https://blog.csdn.net/PoPoQQQ/article/details/46853933
求异或和当然要逐位考虑。第 \(i\) 位的结果是:
\[(\sum_{i=0}^{\lfloor\frac{y-x}{z}\rfloor} \lfloor\frac{x+iz}{2^i}\rfloor)\mod 2
\]
这个就是经典的类欧问题了。
\[\sum_{x=0}^N \lfloor\frac{ax+b}{c}\rfloor = N\lfloor\frac{aN+b}{c}\rfloor-\sum_{x=0}^{\lfloor\frac{aN+b}{c}\rfloor-1} \lfloor\frac{cx+c-b-1}{a}\rfloor
\]
时间复杂度 \(O(\log^2 n)\)。
int64 calc(int64 a,int64 b,int64 c,int64 n){
if(a==0 or (a*n+b)/c==0)
return (a*n+b)/c*(n+1);
if(a>=c)
return a/c*n*(n+1)/2+calc(a%c,b,c,n);
if(b>=c)
return b/c*(n+1)+calc(a,b%c,c,n);
return (a*n+b)/c*n-calc(c,c-b-1,a,(a*n+b)/c-1);
}
int main(){
for(int64 x,y,z;scanf("%lld%lld%lld",&x,&y,&z)!=EOF;){
int64 ans=0;
for(int i=0;i<32;++i)
ans|=(calc(z,x,1LL<<i,(y-x)/z)&1)<<i;
printf("%lld\n",ans);
}
return 0;
}
静渊以有谋,疏通而知事。