XOR
(xor.cpp/.c)
[Title description]
Given a positive integer n, in the range of [1,n], find out how many pairs of unordered numbers (a,b) satisfy gcd(a,b )=a xor b. 【Input format】Enter a total of one line, a positive integer n. [Output format] The output is one line, and a positive integer represents the answer. 【Input and output example】【Input example】3 【Output example】1 【Example explanation】Only (2,3) meet the requirements. 【Data range】For 30% of the data, n≤1000. For 60% of the data, n≤10^5. For 100% of the data, n≤10^7.
The main idea of the title: Given n, find how many gcd(a,b)==a^b; (unordered) in [1,n];
Assuming a>b, we know that gcd(a,b)=gcd(ab,b), and the gcd of two positive integers must not exceed these two numbers, so gcd(a,b)≤ab
Let the i-th bit of a be x and the i-th bit of b be y.
When x=1 or x=y=0, both xy=x xor y.
When x=0 and y=1, there are x xor y=1, xy=-1, that is, x xor y>xy.
So, we get a xor b ≥ ab.
So gcd(a,b)=a^b=ab;
Set c=ab, then there is gcd(a,ac)=c, that is, we need to satisfy that a is a multiple of c and a≠c
Complexity: There are [n/i] multiples of i in [1,n], so the complexity is: nlogn;
#include <bits/stdc++.h> using namespace std; int f[10000001]; int main() { int n; cin>>n; for(int i=1;i<=5000000;i++){ for(int j=i*2;j<10000000;j+=i){ int b=j-i; if((j^b)==i) f[j]++; } } for(int i=1;i<=n;i++) f[i]+=f[i-1]; cout<<f[n]; }
Reprinted in: https://www.cnblogs.com/kamimxr/p/11607728.html