poj 1091 容斥定理

题目传送门

//容斥定理
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=100+5;
int fac[maxn],cnt;
LL n,m,k,temp;
LL pow(LL a,LL b)
{
    LL res=1;
    while(b)
    {
        if(b&1) res=res*a;
        b>>=1;
        a=a*a;
    }
    return res;
}
int a[maxn];
void dfs(int b,int x,int pos)
{
    if(x==pos) {
        LL x1=1,x2;
        for(int i=1;i<=pos;i++)
            x1*=a[i];
        //cout<<x1<<endl;
        x2=k/x1;
        temp+=pow(x2,n);
        return;
    }
    for(int i=b;i<cnt;i++)
    {
        a[x+1]=fac[i];
        dfs(i+1,x+1,pos);
    }
}
int main()
{
    while(scanf("%lld%lld",&n,&m)==2)
    {
        cnt=0;
        k=m;
        for(int i=2;1l*i*i<=m;i++)
        {
            if(m==1) break;
            if(m%i==0) {
                fac[cnt++]=i;
                while(m%i==0) m/=i;
            }
        }
        if(m!=1) {
            fac[cnt++]=m;
        }
        //for(int i=0;i<cnt;i++)
       //      cout<<fac[i]<<endl;
        //cout<<cnt<<endl;
        LL sum=pow(k,n),ans=0;
        //容斥定理,寻找原问题的逆问题
        for(int i=1;i<=cnt;i++)
        {
            temp=0;
            dfs(0,0,i);
            if(i&1) ans+=temp;
            else ans-=temp;
        }
        sum-=ans;
        printf("%lld\n",sum);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值