【HDU 4135 Co-prime】容斥定理+质因数分解

HDU4135
题意
求A-B之间与N互质的数的个数
做法
我们首先对N分解质因数,再对其所有因子进行容斥,最后能得到所有与N不互质的数的个数,最后用n减去这个个数,就是与n互质的数的个数。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
vector<int> v;
ll cal(ll n,ll x)
{
    ll ans=0;
    v.clear();
    for(ll i=2;i*i<=x;i++)
    {
        if(x%i==0)
        {
            v.push_back(i);
            while(x%i==0) x/=i;
        }
    }
    if(x>1) v.push_back(x);

    int sz=v.size();
    for(int i=0;i<(1<<sz);i++)
    {
        int num=0;
        ll tmp=1;
        for(int j=0;j<sz;j++)
        {
            if(i&(1<<j))
            {
                num++;
                tmp*=v[j];
            }
        }
        tmp=n/tmp;
        if(num&1) ans-=tmp;
        else ans+=tmp;
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    int cnt=1;
    while(t--)
    {
        ll a,b,n;
        scanf("%lld%lld%lld",&a,&b,&n);
        ll ans=cal(b,n)-cal(a-1,n);
        printf("Case #%d: %lld\n",cnt++,ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38891827/article/details/82624495