Introduction to Lucas Theorem (Luogu P3807)

content

Assume p is a prime number, then C n m C n / p m / p C n   m O d   p m   m O d   p ( mod p )

Prove

Will not

application

It's just a definition.

You can quickly determine the parity of a combined number. ( p = 2

There is also an extension Lucas that solves p Not a prime number (to be filled).

Code

Take Luogu P3807 as an example.

It can be implemented recursively.

because C n m = n ! m ! ( n m ) ! , so the inverse element is used. It can be linearly pushed or solved by extended Euclidean.

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 200005
using namespace std;
typedef long long LL;
int t,n,m,p; LL c[N],iv[N];
inline void Make(){//线性推逆元
    c[0]=c[1]=iv[0]=iv[1]=1;
    for (int i=2;i<=n+m;i++){
        c[i]=c[i-1]*i%p;
        iv[i]=p-p/i*iv[p%i]%p;
    }
    for (int i=2;i<=n+m;i++)
        iv[i]=iv[i-1]*iv[i]%p; 
}
LL lucas(int x,int y){
    if (x<y) return 0;
    if (x<p) return c[x]*iv[y]%p*iv[x-y]%p;
    return lucas(x/p,y/p)*lucas(x%p,y%p)%p;
}
int main(){
    scanf("%d",&t);
    while (t--){
        scanf("%d%d%d",&n,&m,&p),Make(); 
        printf("%lld\n",lucas(n+m,m));
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324704243&siteId=291194637