HDU 1695 GCD(求两区间的互质数对+容斥原理)
Description
Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = k. GCD(x, y) means the greatest common divisor of x and y. Since the number of choices may be very large, you're only required to output the total number of different number pairs.
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same.
Yoiu can assume that a = c = 1 in all test cases.
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same.
Yoiu can assume that a = c = 1 in all test cases.
Input
The input consists of several test cases. The first line of the input is the number of the cases. There are no more than 3,000 cases.
Each case contains five integers: a, b, c, d, k, 0 < a <= b <= 100,000, 0 < c <= d <= 100,000, 0 <= k <= 100,000, as described above.
Each case contains five integers: a, b, c, d, k, 0 < a <= b <= 100,000, 0 < c <= d <= 100,000, 0 <= k <= 100,000, as described above.
Output
For each test case, print the number of choices. Use the format in the example.
Sample Input
2
1 3 1 5 1
1 11014 1 14409 9
Sample Output
Case 1: 9
Case 2: 736427
Hint
For the first sample input, all the 9 pairs of numbers are (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5).
b,d除于k,转化为求互质对
用容斥原理求出所有不互质的数对数,再用整数减去!
#include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include <cstring> using namespace std; #define LL long long #define N 111111 int a,b,c,d,k; LL ans; vector<int> prime[N]; bool vis[N]; void init(){ memset(vis,false,sizeof vis); for(int i=0;i<=N;i++) prime[i].clear(); for(int i=2;i<=N;i+=2) prime[i].push_back(2);//这样快很多 for(int i=3;i<=N;i+=2) if(!vis[i]){ for(int j=i;j<=N;j+=i){ prime[j].push_back(i);vis[j]=true; } } } void fun(int x,LL y,int z){ LL v = 1,cnt=0; for(int i=0;i<prime[x].size();i++){ if(1<<i&y){ v*=prime[x][i]; cnt++; } } if(cnt&1) ans-=z/v; else ans+=z/v; } int main() { init();int _,o;scanf("%d",&_);o=_; while(_--){ printf("Case %d: ",o-_);ans=0; scanf("%d%d%d%d%d",&a,&b,&c,&d,&k); if(!k) {puts("0");continue;} b/=k,d/=k;int z;if(d<b) z=d,d=b,b=z; for(int i=1;i<=d;i++){ int k = min(i,b);ans+=k;//保证不重复 for(LL j=1;j<(1<<prime[i].size());j++) fun(i,j,k); } printf("%lld\n",ans); } return 0; }