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.

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

分析

这个题的题意就是说给你两个区间,求有多少对(x,y),x从第一个区间中选,y从第二个区间中选,使得gcd(x,y) = k,这个题的话简化一下把a,b,c,d都除以k,那么就是咱们要求的范围了,但是这个输入的话听别人说是左边界默认为1,说是从题意里读出来的,属实是咱这英语水平不太行了哈哈哈,下面请看莫比乌斯反演解题的推理
在这里插入图片描述

总结

当某个函数不易求得,但他的约数的函数值之和容易求或者倍数的函数值之和容易求的时候可以考虑莫比乌斯反演

代码

#include<iostream>
using namespace std;
const int N = 100010;
typedef long long LL;
int mobius[N],primes[N],cnt;
bool st[N];
void init(int n){
	mobius[1] = 1;
	for(int i=2;i<=n;i++){
		if(!st[i]){
			primes[cnt++] = i;
			mobius[i] = -1;
		}
		for(int j=0;j<cnt && primes[j]*i <= n;j++){
			int t = i * primes[j];
			st[t] = true;
			if(i % primes[j] == 0){
				mobius[t] = 0;
				break;
			}
			mobius[t] = -mobius[i];
		}
	}
}
LL solve(LL a,LL b){
	LL ans = 0;
	LL minn = min(a,b);
	for(LL i=1;i<=minn;i++){
		ans += mobius[(int)i] * (a/i) * (b/i);
	}
	return ans;
} 
int main(){
	init(N-1);
	int T;
	cin>>T;
	for(int i=1;i<=T;i++){
		cout<<"Case "<<i<<": ";
		LL a,b,c,d,k;
		cin>>a>>b>>c>>d>>k;
		if(k == 0){//这是个坑,注意别踩进去哈哈哈
			 printf("0\n",i);
			continue;
		}
		b /= k;
		d /= k;
		LL ans = 0;
		if(b > d) swap(b,d);
		ans += solve(b,d);
		ans -= solve(b,b)/2;
		cout<<ans<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇智波一打七~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值