逆元線性打表後求大組合數(m≤10^6)

在這裏插入圖片描述
逆元求組合數中作用就是講公式中的除法取餘轉化爲乘法取餘,其實當m≤10^5時,都可以直接暴力求分子中每個因子的逆元(會用到快速冪),這裏需要先求出p的歐拉函數值。 此處n,p的值在數據範圍(10^18)內就行

除了上面的思路,我們也可以O(n)打表得出1!~n!的逆元對p取模後的結果:求逆元的方法總結、打表,這時就不需要用到快速冪求逆元,但此時對n的範圍就有要求了:n≤10^6, m≤10^6

打表代碼實現:
注意:需要滿足條件n<p

inv[1]=1;
for(int i=2;i<=n;++i)
  inv[i]=p-p/i*inv[p%i]%p;
for(int i=2;i<=n;++i)
  inv[i]=(inv[i]*inv[i-1])%p;

例題1:P3807 【模板】盧卡斯定理
代碼:

#include <iostream>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#define mod 1000000007
#include<string.h>
using namespace std;
typedef long long LL;
const int manx=2e5+7;
LL a[manx],b[manx];
LL Lucas(LL n,LL m,LL p)
{
    if(n<m) return 0;
    else if(n<p) return (b[n]*a[m]%p)*a[n-m]%p;
    else return Lucas(n/p,m/p,p)*Lucas(n%p,m%p,p)%p;
}
int main()
{
     LL n,m,p,t;
     scanf("%lld",&t);
     while(t--)
     {
          scanf("%lld%lld%lld",&n,&m,&p);
          a[0]=a[1]=b[0]=b[1]=1;
          for(int i=2;i<=n+m;i++) b[i]=b[i-1]*i%p;
          for(int i=2;i<=n+m;i++) a[i]=(p-p/i)*a[p%i]%p;
          for(int i=2;i<=n+m;i++) a[i]=a[i-1]*a[i]%p;
          printf("%lld\n",Lucas(n+m,m,p));
     }
}

因爲這裏n+m可能會大於p,所以需要用盧卡斯轉化一下。

例題2:power-oj2816: Alice的編程之旅
在這裏插入圖片描述
輸入包含T(1≤T≤106)組數據。
接下來T行,每行包含兩個正整數n,m。(1≤m≤n≤105

用上面的方法,可以先將1~n的階乘階乘的逆元打表後,O(1)得到結果:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
typedef unsigned long long LL;
const LL manx=1e5+10;
const LL p=1e9+7;
LL inv[manx],a[manx];
int main()
{
    int n,m,t;
    a[0]=a[1]=inv[0]=inv[1]=1;
    for(int i=2;i<=1e5;i++)
        inv[i]=(p-p/i)*inv[p%i]%p;
    for(int i=2;i<=1e5;i++)
    {
        a[i]=i*a[i-1]%p;
        inv[i]*=inv[i-1];
        inv[i]%=p;
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        LL ans=1;
        ans*=a[n];
        ans%=p;
        ans*=inv[m];
        ans%=p;
        ans*=inv[n-m];
        ans%=p;
        printf("%lld\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章