原题:
Given an integer N, find 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 first 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 first 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) and (7, 6).
Sample Input
2
7
20000000
Sample Output
Case 1: 4
Case 2: 34866117
大意:
意思很简单,给你一个数n,让你找这样两个数a,b其中1 ≤ b ≤ a ≤ n.而且gcd(a,b)=a xor b
问题有多少个满足上述公式的个数。
#include <bits/stdc++.h>
using namespace std;
constexpr int inx=30000000;
int table[inx+1];
int main()
{
ios::sync_with_stdio(false);
for(int c=1;c<=inx/2;c++)
{
for(int a=c+c;a<=inx;a+=c)//a等于n倍的c,所以c此时是a的约数
if((a^(a-c))==c)
++table[a];
}
for(int i=2;i<=inx;i++)
table[i]+=table[i-1];
int n,t,k=1;
cin>>t;
while(t--)
{
cin>>n;
cout<<"Case "<<k++<<": "<<table[n]<<endl;
}
return 0;
}
解答:
紫书上的例题,自己想的时候感觉要枚举位数,3千万大概是24位。后来枚举结果不正确,看了书上的思路和别人的代码后交过了。
书上的思路是枚举a和a的约数,因为a xor b = c,那么a xor c = b。可以用筛法求a的约数。此外,可以代表找规律,gcd(a,b)=a xor b=c 其中c=a-b! 如此就可以不用gcd公式。
头一次见到数组能开3千万这么大!