hdu4135 Co-prime(容斥)

题目链接:点这里!!!!


题意:

给你一个区间[A,B](1<=A<=B<=1E15),一个x(x<=1e9)。问你[A,B]区间内有多少个数与x互质。


题解:

1、我们先把x的所有质因子找出来,注意x的最多存在1个质因子大于(sqrt(x)),所以我们可以先预处理出[1,sqrt(1e9)]所有的质数。


2、然后我们把x质因子分解并往下除,最后剩下的要么是1,要么就是大于sqrt(x)的质因子。


3、我们得到的质因子最多15个左右,我们直接利用容斥搞就可以了。我们得出的是与x不互质数的个数,利用总数减去就可。



代码;



#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<cstdlib>
#include<cmath>
#define PI 2*asin(1.0)
#define LL long long
#define pb push_back
#define pa pair<int,int>
#define clr(a,b) memset(a,b,sizeof(a))
#define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r
#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)
#define key_value ch[ch[root][1]][0]C:\Program Files\Git\bin
const LL  MOD = 1E9+7;
const LL N = 3e4+5000;
const int maxn = 5e5+15;
const int letter = 130;
const int INF = 1e17;
const double pi=acos(-1.0);
const double eps=1e-10;
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
LL a,b;
int x;
int vis[N],cnt=0;
int prime[10000],ps[32];
void init(){
    vis[1]=1;
    for(int i=2;i<N;i++){
        if(!vis[i]) prime[++cnt]=i;
        for(int j=1;j<=cnt&&i*prime[j]<N;j++){
            vis[prime[j]*i]=1;
            if(i%prime[j]==0) break;
        }
    }
}
int main(){
    init();
    int T,cas=0;
    scanf("%d",&T);
    while(T--){
        scanf("%I64d%I64d%d",&a,&b,&x);
        int num=0;
        for(int i=1;i<=cnt;i++){
            if(x%prime[i]==0){
                while(x%prime[i]==0){
                    x/=prime[i];
                }
                ps[num++]=prime[i];
            }
        }
        if(x!=1) ps[num++]=x;
        LL sum=b-a+1ll;
        LL tt=0;
        for(int i=1;i<(1<<num);i++){
            int cc=0;
            LL ans=1;
            for(int j=0;j<num;j++){
                if(i&(1<<j)){
                    cc++;
                    ans*=1ll*ps[j];
                }
            }
            if(cc&1) tt=tt+(b/ans-(a-1)/ans);
            else tt=tt-(b/ans-(a-1)/ans);
        }
        printf("Case #%d: %I64d\n",++cas,sum-tt);
    }
    return 0;
}
/*
100
3 15 12

*/


给你一个区间[A,B](1<=A<=B<=1E15),一个x(x<=1e9)。问你[A,B]区间内有多少个数与x互质。


题解:

1、我们先把x的所有质因子找出来,注意x的最多存在1个质因子大于(sqrt(x)),所以我们可以先预处理出[1,sqrt(1e9)]所有的质数。


2、然后我们把x质因子分解并往下除,最后剩下的要么是1,要么就是大于sqrt(x)的质因子。


3、我们得到的质因子最多15个左右,我们直接利用容斥搞就可以了。我们得出的是与x不互质数的个数,利用总数减去就可。



代码;


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值