题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1119
题目:
第1行,2个数M,N,中间用空格隔开。(2 <= m,n <= 1000000)
输出走法的数量 Mod 10^9 + 7。
求组合数C(n+m-2,n-1)%Mod。带模除法用费马小定理:
费马小定理:假如p是素数,且a与p互质,那么a^(p-1) = 1 (mod p)。
带模的除法:求 a / b = x (mod M)
只要 M 是一个素数,而且 b 不是 M 的倍数,就可以用一个逆元整数 b’,通过 a / b = a * b' (mod M),来以乘换除。
费马小定理说,对于素数 M 任意不是 M 的倍数的 b,都有:b ^ (M-1) = 1 (mod M)
于是可以拆成:b * b ^ (M-2) = 1 (mod M)
于是:a / b = a / b * (b * b ^ (M-2)) = a * (b ^ (M-2)) (mod M)
也就是说我们要求的逆元就是 b ^ (M-2) (mod M)! ——(用快速幂可以求出)
#include <iostream>
#include<bits/stdc++.h>
//#define MOD 1000000007
#define LL long long
using namespace std;
const LL MOD=1000000007;
LL f[2200000];
void init()
{
f[1]=1;
for(int i=2;i<=2000000;i++)
f[i]=(f[i-1]*i)%MOD;
}
LL pow(LL n, LL m)
{
LL ans=1;
while(m)
{
if(m&1) ans=(ans*n)%MOD;
m=m>>1;
n=(n*n)%MOD;
}
return ans;
}
LL solve(LL n,LL m)
{
long long ans=f[m+n-2];
ans=(ans*pow(f[m-1],MOD-2))%MOD;
ans=(ans*pow(f[n-1],MOD-2))%MOD;
return ans;
}
int main()
{
init();
LL n,m;
scanf("%lld%lld",&n,&m);
cout<<solve(n,m)<<endl;
}