Gym - 101982B 2018-2019 ACM-ICPC Pacific Northwest Regional Contest (Div. 1) B. Coprime Integers Mobius+容斥 ab间gcd(x,y)=1的对数
题意:给你 abcd(1e7),求a<=x<=b,c<=y<=d的,gcd(x,y)=1的数量
题解:经典题目,求从1的到n中选x,从1到m中选y的,gcd(x,y)=k的可以看hdu1695
ask(x,y)表示从1到n中选n,从1到m中选y的话
ans=ask(b,d)-ask(b,c-1)-ask(a-1,d)+ask(a-1,c-1)
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const ll maxn = 1e7 + 10; 5 ll mu[maxn], check[maxn], prime[maxn]; 6 void Euler() 7 { 8 int tot = 0; 9 mu[1] = 1; 10 check[1] = true; 11 for (int i = 2; i < maxn; i++) { 12 if (!check[i]) { 13 prime[++tot] = i; 14 mu[i] = -1; 15 } 16 for (int j = 1; j <= tot; j++) 17 { 18 if ((ll)prime[j] * i >= maxn) break; 19 check[i*prime[j]] = true; 20 if (i%prime[j] == 0) 21 { 22 mu[i*prime[j]] = 0; 23 break; 24 } 25 else mu[i*prime[j]] = mu[i] * -1; 26 } 27 } 28 } 29 int a, b, c, d; 30 ll why(int l,int r) 31 { 32 ll ans=0; 33 for (int i=1;i<=min(l, r);i++) 34 ans+=(ll)(l/i)*(r/i)*mu[i]; 35 return ans; 36 } 37 int main() 38 { 39 Euler(); 40 cin >> a >> b >> c >> d; 41 cout<<why(b,d)-why(b,c-1)-why(a-1,d)+why(a-1,c-1); 42 }
Anderyi!