hdu1695 GCD(莫比乌斯反演)
题意:求(1,b)区间和(1,d)区间里面gcd(x, y) = k的数的对数(1<=x<=b , 1<= y <= d)。
知识点:
线性筛求莫比乌斯反演函数:
void Init() { memset(vis,0,sizeof(vis)); mu[1] = 1; cnt = 0; for(int i=2; i<N; i++) { if(!vis[i]) { prime[cnt++] = i; mu[i] = -1; } for(int j=0; j<cnt&&i*prime[j]<N; j++) { vis[i*prime[j]] = 1; if(i%prime[j]) mu[i*prime[j]] = -mu[i]; else { mu[i*prime[j]] = 0; break; } } } }
题解:
转化题意就是[1,n/k],[1,m/k]之间互质的数的个数。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int N=100000+10; int u[N],prime[N]; bool vis[N]; void init() { memset(vis,0,sizeof(vis)); u[1] = 1; int cnt = 0; for(int i=2; i<N; i++) { if(!vis[i]) { prime[cnt++] = i; u[i] = -1; } for(int j=0; j<cnt&&i*prime[j]<N; j++) { vis[i*prime[j]] = 1; if(i%prime[j]) u[i*prime[j]] = -u[i]; else { u[i*prime[j]] = 0; break; } } } } int main() { init(); int t; cin>>t; int a,b,c,d,k; for(int kase=1;kase<=t;kase++) { scanf("%d%d%d%d%d",&a,&b,&c,&d,&k); if(k==0) { printf("Case %d: 0\n",kase); continue; } long long ans=0; int ma=max(b,d),mi=min(b,d); for(int i=k;i<=mi;i+=k) { ans+=(long long)u[i/k]*((ma/i)*2-(mi/i)+1)*(mi/i)/2; } printf("Case %d: %I64d\n",kase,ans); } return 0; }
GCD
Time Limit:3000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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.
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.
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).