您的位置:首页 > 编程语言 > C语言/C++

UVa 12716 GCD XOR

2016-11-03 23:56 323 查看
Given an integer N, find how many pairs (A, B) are there such that: gcd(A, B) = A xor B where1 ≤ B ≤ A ≤ N.Here gcd(A, B) means the greatest common divisor of the numbers A and B. And A xor B is thevalue
of the bitwise xor operation on the binary representation of A and B.

Input

The first line of the input contains an integer T (T ≤ 10000) denoting the number of test cases. Thefollowing T lines contain an integer N (1 ≤ N ≤ 30000000).

Output

For each test case, print the case number first in the format, ‘Case X:’ (here, X is the serial of theinput) 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) and (7, 6).

Sample Input

2

7

20000000

Sample Output

Case 1: 4

Case 2: 34866117

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

位运算+数学推导+枚举~

1.a xor b=c-->a xor b=b;

2.a-b<=a xor b=c;

3.a=k1*c,b=k2*c,则k1>k2;a-b=(k1-k2)*c>=c;

由上述三个结论可得a-b=c,然后就枚举c和a,计算b即可~

#include<cstdio>

int t,n,cnt,ans[30000001],num,k;

int main()
{
k=30000000>>1;
for(int i=1;i<=k;i++)
for(int j=i*2;j<=30000000;j+=i)
{
num=j-i;
if((j^num)==i) ans[j]++;
}
for(int i=2;i<=30000000;i++) ans[i]+=ans[i-1];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("Case %d: %d\n",++cnt,ans
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 数论