P2480 [SDOI2010] 古代猪文

· · 算法·理论

题意转述

给出n,g,求g^{\sum\limits_{k|n}{C_n^k}}(mod\ 999911659)

数学推导

费马小定理

若p为素数,gcd(a,p)=1,则a^{p-1}=1(mod\ p)

因此,当g\ mod\ 999911659 =0时,特判答案为0,否则原式就转化为了

g^{\sum\limits_{k|n}{C_n^k}\ mod\ 999911658}(mod\ 999911659)

令x=\sum\limits_{k|n}{C_n^k}\ mod\ 999911658,由于n和模数都很大,无论是递推预处理还是暴力硬算都行不通。这里提供另一种求解组合数的方法,lucas定理。

lucas定理

lucas定理适合求解组合数较大但是模数是一个小质数的情况。模版 Lucas定理

C_n^k=C_{\lfloor n/p\rfloor}^{\lfloor k/p\rfloor}*C_{n\ mod\ p}^{k\ mod\ p}(mod\ p) n<k$时,令$C_n^k=0

证明

然而对于这道题,999911658既不是质数也不小,要将它转换成能用lucas定理解决的问题,还需要别的工具。

中国剩余定理(CRT)

中国剩余定理常常用来求解一元线性同余方程组(模数互质),在这道题中我们将对于999911658取模拆成若干个一元线性方程,分别求解后用CRT合并,就可以解决。

可以发现,在模数互质的情况下,一元线性同余方程组的解是一个对原来模数的积取模的一元线性方程。因此我们将999911658质因数分解,得到

999911658=2*3*4679*35617

因此,我们求解同余方程组

\end{cases}

就可以得到\sum\limits_{k|n}{C_n^k}\ mod\ 999911658的值。

对于\sum\limits_{k|n}{C_n^k}\ mod\ 2/3/4679/35617的部分,用卢卡斯定理求组合数即可。

复杂度分析

瓶颈在处理约数和求lucas,总复杂度O(\sqrt{N}log_2N),跑得飞快。

代码

#include<bits/stdc++.h>
using namespace std;
#define int long long
namespace fastIO
{
    void read(int &res)
    {
        int f=1;res=0;
        char c=getchar();
        while(c<'0'||c>'9')
        {
            if(c=='-')f=-1;
            c=getchar();
        }
        while(c>='0'&&c<='9')
        {
            res=(res<<3)+(res<<1)+(c^48);
            c=getchar();
        }
        res*=f;
    }
    void write(int x)
    {
        if(x<0)putchar('-'),x=-x;
        if(x>9)write(x/10);
        putchar((x%10)|48);
    }
}
using namespace fastIO;
const int Mod=999911659;
const int M=999911658;
int ni[5]={0,2,3,4679,35617};
int n,g;
int inv[40005],fac[40005];
int lucas(int x,int k,int p){
    if(x<k)return 0;
    if(x<p)return fac[x]*inv[k]%p*inv[x-k]%p;
    return lucas(x/p,k/p,p)*lucas(x%p,k%p,p)%p;
}
void Init(int up,int p){
    inv[0]=inv[1]=fac[0]=fac[1]=1;
    for(int i=2;i<=up;i++)fac[i]=fac[i-1]*i%p;
    for(int i=2;i<=up;i++)inv[i]=(p-p/i)*inv[p%i]%p;
    for(int i=2;i<=up;i++)inv[i]=inv[i]*inv[i-1]%p;
}
inline int ksm(int a,int k,int p){
    int res=1ll;
    while(k){
        if(k&1ll)res=res*a%p; 
        a=a*a%p;
        k>>=1ll;
    }
    return res;
}
int ans;
signed main()
{
    read(n);read(g);
    if(g%Mod==0)return puts("0"),0;
    for(int i=1;i<=4;i++){
        int p=ni[i],Mi=M/p;
        int tmp=0;
        Init(p,p);
        for(int j=1;j*j<=n;j++){
            if(n%j!=0)continue;
            tmp=(tmp+lucas(n,j,p))%p;
            if(j*j!=n)
            tmp=(tmp+lucas(n,n/j,p))%p;
        }
        int ci=Mi*ksm(Mi,p-2,p)%M;
        ans=(ans+ci*tmp%M);
    }
    write(ksm(g,ans,Mod));
    return 0;
}