hdu4135 Co-prime 容斥原理

本文介绍了一种使用容斥原理解决特定数学问题的方法:计算两个给定整数范围内与另一给定整数互质的所有整数的数量。通过分解给定整数的所有质因数并运用容斥原理进行计算。

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

Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

容斥原理

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 typedef long long ll;
 7 
 8 int pnum[500];
 9 
10 int main(){
11     int T;
12     scanf("%d",&T);
13     for(int q=1;q<=T;++q){
14         ll a,b;
15         int n;
16         scanf("%lld%lld%d",&a,&b,&n);
17         a--;
18         ll ans=0;
19         int cnt=0;
20         for(int i=2;i*(ll)i<=n;++i){
21             if(!(n%i)){
22                 pnum[++cnt]=i;
23                 while(!(n%i))n/=i;
24             }
25         }
26         if(n>1)pnum[++cnt]=n;
27         for(int i=1;i<(1<<cnt);++i){
28             int bit=0;
29             int mul=1;
30             for(int j=1;j<=cnt;++j){
31                 if(i&(1<<(j-1))){
32                     bit++;
33                     mul*=pnum[j];
34                 }
35             }
36             if(bit%2)ans+=b/mul-a/mul;
37             else ans-=b/mul-a/mul;
38         }
39         printf("Case #%d: %lld\n",q,b-a-ans);
40     }
41     return 0;
42 }
View Code

 

转载于:https://www.cnblogs.com/cenariusxz/p/6597970.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值