Given an integer N , nd how many pairs ( A;B ) are there such that:
gcd( A;B ) = A xor B where 1 B A N . Here gcd( A;B ) means the
greatest common divisor of the numbers A and B . And A xor B is the
value of the bitwise xor operation on the binary representation of A
and B . Input The rst line of the input contains an integer T ( T
10000) denoting the number of test cases. The following T lines
contain an integer N (1 N 30000000). Output For each test case,
print the case number rst in the format, ` Case X : ’ (here, X is the
serial of the input) followed by a space and then the answer for that
case. There is no new-line between cases. Explanation Sample 1: For N
= 7, there are four valid pairs: (3, 2), (5, 4), (6, 4)
做法一:枚举a,枚举b,验证a^b=gcd(a,b)。时间复杂度O(n^2logn)。
做法二:枚举a,枚举a的因数c,根据异或运算的性质计算b=a^c,验证c=gcd(a,b)。用Eratosthenes筛法枚举a和c复杂度O(nlogn),总复杂度O(nlogn^2)。
做法三:注意到a^b>=a-b>=gcd(a,b)【前一条考虑0^0=0-0,1^1=1-1,0^1>0-1,1^0=1-0,后一条根据辗转相减法】。因此在枚举a和c之后,取b=a-c,则必有gcd(a,b)=gcd(a,a-c)=c,只需要验证b=a^c即可。时间复杂度O(nlogn)。
#include<cstdio>
#include<cstring>
#define LL long long
const int maxn=30000000;
LL cnt[maxn+5],ans[maxn+5];
int main()
{
int i,j,k,m,n,p,q,x,y,z,T,K;
for (i=1;i<=maxn;i++)
for (j=i*2;j<=maxn;j+=i)
if ((j^i)==j-i) cnt[j]++;
for (i=1;i<=maxn;i++)
ans[i]=ans[i-1]+cnt[i];
scanf("%d",&T);
for (K=1;K<=T;K++)
{
scanf("%d",&n);
printf("Case %d: %lld\n",K,ans[n]);
}
}

本文探讨了给定整数N时寻找满足条件gcd(A;B)=A xor B的所有数对(A;B)的方法。提出了三种不同的算法实现方案,包括直接枚举验证、基于因数的枚举以及通过观察不等式特性简化计算过程。最终实现了一个高效的时间复杂度为O(nlogn)的算法。

603

被折叠的 条评论
为什么被折叠?



