题目链接:https://ac.nowcoder.com/acm/contest/634/C
题目大意:给出L,R,k三个参数(L,R数据范围在1e18, k的范围在1e13),然后在区间[L, R]找出有多少个数y,满足y - k, y + k互质的(y-k, y+k满足在[L,R]区间内)。
题解:
分析
暴力枚举质因数的复杂度为根号k,容斥的复杂度大致为k*logk
ps: 容斥这边是将所有的质因子做一个全排列,表示出所有公倍数。
code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
ll L, R, k;
ll a[maxn], cnt;
ll solve(ll x) {
if(x < 0) {
return 0;
}
ll ans = 0;
for(ll S = 0; S < 1 << cnt; S ++) {
ll p = 1, f = 1;
for(int i = 0;i < cnt; i ++) {
if((1 << i) & S ) {
p *= a[i];
f *= -1;
}
}
ans += x / p * f;
}
return ans;
}
int main() {
while(cin >> L >> R >> k) {
cnt = 0;
k <<= 1;
R -= k;
if(L > R) {
cout << 0 << endl;
continue;
}
for(int i = 2;i * i <= k; i ++) {
if(k % i == 0) {
a[cnt ++] = i;
while(k % i == 0) {
k /= i;
}
}
}
if(k > 1) {
a[cnt ++] = k;
}
cout << solve(R) - solve(L - 1) << endl;
}
return 0;
}