UVA 12716 GCD XOR (素数筛法思想+打表规律)

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) and (7, 6)

Sample Input

2

7

20000000

Sample Output

Case 1: 4

Case 2: 34866117

#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<queue>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll long long
#define maxn 30000005
#define eps 0.0000001
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") ///在c++中是防止暴栈用的
/*
题目大意:给定一个数为n,
n为a,b的上界,
问有多少二元组(a,b)满足a<=b
并且gcd(a,b)=a xor b.

紫书上的例题:
首先找xor的数学性质,
如果a xor b =c,
则一定有 a xor c = b;
基于这个性质我们可以想到枚举a和c,
其中c是a的因子,利用素数筛法的思想进行。
复杂度为O(n*(logn)^2),比较高了,
至少我预处理这样肯定要超时了。
那么打表找规律。。。发现
满足题意的a和b都是:
a-b=c这样的关系。
这样就可以消去一个log的复杂度,就是省去了求gcd的时间因子
*/
int n,t,ca;
int cnt[maxn];
void get_prime(int ub)
{
    memset(cnt,0,sizeof(cnt));
    for(int i=1;i<ub;i++)///加个等于号就被判wrong。。。不知道为何
        for(int j=2*i;j<ub;j+=i)
        {
            if( ( (j-i)^j )== i )
                cnt[j]++;
        }
}

int main()
{
    get_prime(maxn);
    for(int i=1;i<maxn;i++) cnt[i]+=cnt[i-1];
    scanf("%d",&t);///cout<<t<<endl;
    while(t--)
    {
       scanf("%d",&n);
       printf("Case %d: %d\n",++ca,cnt[n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81194640