Uva12716:GCD XOR

来源:互联网 发布:淘宝天猫内购券 编辑:程序博客网 时间:2024/06/01 07:38

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.

Sample Input

2720000000

Sample Output

Case 1: 4Case 2: 34866117

Explanation

Sample 1: For N = 7, there are four valid pairs: (3, 2), (5, 4), (6, 4) and (7, 6).

【题目描述】

给你一个正整数n,问你区间[1, n]中有多少无序数对(a, b)满足gcd(a,b)=ab

【简要题解】

假设a>b,我们可以观察到

ab>=ab

gcd(a,b)ab

第一个不等式是显然的。
而由于gcd(a,b)|bgcd(a,b)|b
所以gcd(a,b)|ab,所以第二个不等式也成立
所以就有gcd(a,b)=ab
我们可以枚举c=gcd(a,b),再枚举a=ci,判断ac是否等于ac即可

时间复杂度:O(nlogn)

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;int solve(int n){    int ans = 0, e = n >> 1;    for(int c = 1; c <= e; ++c)        for(int a = c << 1; a <= n; a += c)            if((a^c) == a-c) ans++;    return ans;}int main(){    int n; cin >> n;    cout << solve(n) << endl;    return 0;}
0 0
原创粉丝点击