HDU - 5072(容斥原理)

题意:给你a,b,n,问区间[a, b]内有多少数与n互素?

解题思路:问题可以转化为求1到b内与n互素的个数减去1到a-1内与n互素的问题,那么现在的问题就是求1到x内与n互素的个数。要求1到x内与n互素的个数,可以先求不与n互素的个数。不与n互素的个数可以将n质因数分解,n的质因子的倍数肯定不与n互素。

例如x = 15, n = 10。n的质因子有2、5.。(2、4、6、8、10、12、14)->15/2 = 7 (5 、10、15)->15/5 = 3。考虑到其中有重复的,我们用容斥定理

15/2 + 15/5 - 15/(2*5) = 9。所以不与n互质的有9个,那么与n互质的有6个。

#include<cstdio>
#include<set>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e6 + 20;
const double EPS = 1e-5;
const int mod = 1e8 + 7;
typedef unsigned long long ull;
typedef long long LL;
int dx[] = {0, 0, -1, 1, -1, -1, 1, 1};
int dy[] = {1, -1, 0, 0, -1, 1, -1, 1};
long long a, b, n;
int num[maxn];
int cnt;
void init(){
    cnt = 0;
    int s = n;
    for(int i = 2; i * i <= n; ++i){
        if(s % i == 0){
            num[cnt++] = i;
            while(s % i == 0) s /= i;
        }
    }
    if(s > 1) num[cnt++] = s;
}
long long solve(long long x){
    long long ans = 0;
 //   printf("%d\n", cnt);
    for(int i = 1; i < (1 << cnt); ++i){
        int sum = 1;
        int k = 0;
        for(int j = 0; j < cnt; ++j){
            if((1 << j) & i){
                sum *= num[j];
                k++;
            }
        }
        if(k & 1) ans += x / sum;
        else ans -= x / sum;
    }
    return x - ans;
}
int main(){
    int T, kase = 0;
    scanf("%d", &T);
    while(T--){
        scanf("%lld%lld%lld", &a, &b, &n);
        init();
        printf("Case #%d: %lld\n", ++kase, solve(b) - solve(a - 1));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值