uva12716 gcd

时间:2021-02-15 02:34:44

题意:给出N,1<=b<=a<=N,求满足gcd(a,b)=a xor b的pair (a,b)的个数

有个重要的结论:若gcd(a,b)=a xor b=c,那么b=a-c

如果一个个求gcd肯定不行。

令f[i]表示满足条件的pair (a,b)中,a=i的个数

枚举c,令a是c的所有倍数,求出b=a-c。若b=a xor c那么f[a]++

最后求f[]的前缀和S[],那么答案就是S[N](要求a<=N啦~)

 #include <stdio.h>
#include <string.h>
#define LL long long
#define MX 30000005 int N,T;
LL S[MX],f[MX]; int main()
{
memset(f,,sizeof(f));
for (int c=;c<=MX;c++)
for (int a=*c;a<=MX;a+=c)
{
int b=a-c;
if ((a^b)==c)
{
//printf("%d %d %d %d\n",a,b,a^b,c);
f[a]++;
}
} S[]=f[];
for (int i=;i<=MX;i++)
{
//printf("%d ",f[i]);
S[i]=S[i-]+f[i];
} scanf("%d",&T);
for (int times=;times<=T;times++)
{
scanf("%d",&N);
printf("Case %d: %lld\n",times,S[N]);
} return ;
}

reference:http://blog.csdn.net/u013451221/article/details/38512091