HDU/HDOJ 1695 GCD 欧拉函数+容斥原理

本文详细介绍了如何解决HDU平台上的问题HDU 1695,该问题涉及在给定范围内找到满足特定条件的最大公约数的解决方案。文章首先阐述了问题背景和输入输出格式,随后深入探讨了解决策略,包括利用欧拉函数和容斥原理来计算符合条件的数对数量。通过具体的实例分析,展示了如何在有限的范围内寻找满足条件的数对,并最终输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1695

Problem 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).

Source


思路:

以前,单纯的认为GCD和欧拉函数没有半毛钱的关系。

但是现在,这个关系就大了。。

GCD(X,Y)=K----->GCD(X/K,Y/K)=1

这样就是互质了。。

而这个题。我们枚举y,然后看前面x集合里面有多少和他互质的就是答案

至于说把计算这一种情况:在1-x区间,所有与y互质的个数,这个需要用到容斥原理(x<y)

我的代码:

#include<stdio.h> #include<algorithm> #include<vector> using namespace std; typedef __int64 ll; ll prime[100005]; bool flag[100005]; ll phi[100005]; vector<ll>link[100005]; void init()//得到素数以及欧拉函数值 { ll i,j,num=0; phi[1]=1; for(i=2;i<=100000;i++) { if(!flag[i]) { prime[num++]=i; phi[i]=i-1; } for(j=0;j<num&&prime[j]*i<=100000;j++) { flag[prime[j]*i]=true; if(i%prime[j]==0) { phi[i*prime[j]]=phi[i]*prime[j]; break; } else phi[i*prime[j]]=phi[i]*(prime[j]-1); } } for(j=1;j<=100000;j++)//得到所有数包含的素因子 { ll tmp=j; for(i=0;prime[i]*prime[i]<=tmp;i++) { if(tmp%prime[i]==0) { link[j].push_back(prime[i]); tmp=tmp/prime[i]; while(tmp%prime[i]==0) tmp=tmp/prime[i]; } if(tmp==1) break; } if(tmp>1) link[j].push_back(tmp); } } ll dfs(ll x,ll b,ll now)//容斥原理 { ll i,res=0; for(i=x;i<link[now].size();i++) res=res+b/link[now][i]-dfs(i+1,b/link[now][i],now); return res; } int main() { init(); ll i,a,b,t,T,ans,c,d,k; while(scanf("%I64d",&T)!=EOF) { for(t=1;t<=T;t++) { ans=0; scanf("%I64d%I64d%I64d%I64d%I64d",&a,&b,&c,&d,&k); if(k==0||k>b||k>d) { printf("Case %I64d: 0\n",t); continue; } if(b>d) swap(b,d); b=b/k,d=d/k; for(i=1;i<=b;i++) ans=ans+phi[i]; for(i=b+1;i<=d;i++) ans=ans+b-dfs(0,b,i); printf("Case %I64d: %I64d\n",t,ans); } } return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值