Three Fast Methods of Factorial Inverse Element Fermat's Little Theorem Recursive Linear

Three Fast Methods of Factorial Inverse Element Fermat's Little Theorem Recursion Linear

1. Fermat's little theorem

#include<cstdio>
typedef long long LL;
const LL MOD = 1e9 + 7;
LL fac[1000000+5];        //阶乘
LL inv[1000000+5];        //逆元 
LL quickMod(LL a,LL b)
{
	LL ans = 1;
	while (b)
	{
	    if (b&1)
	        ans = ans * a % MOD;
	     a = a*a % MOD;
	     b >>= 1;
	}
	return ans;
}
void getFac()
{
	fac[0] = inv[0] = 1;
	for (int i = 1 ; i <= 1000000 ; i++)
	{
	     fac[i] = fac[i-1] * i % MOD;
	     inv[i] = quickMod(fac[i],MOD-2);        //表示i的阶乘的逆元 
	}
}
LL getC(LL n,LL m)        //C(n,m) = n!/((n-m)!*m!) % (1e9+7)
{
	return fac[n] * inv[n-m] % MOD * inv[m] % MOD;
}
int main()
{
	getFac();
	int n,m;
	while (~scanf ("%d %d",&n,&m))
	     printf ("%lld\n",getC((LL)n,(LL)m));
	return 0;
}

2. Recursively find the factorial inverse

We can consider using Fermat's little theorem to first find the inverse of the largest factorial, and then push it back, look directly at the code and explain.

void init() {
	fact[0] = 1;
	for (int i = 1; i < maxn; i++) {
		fact[i] = fact[i - 1] * i %mod;
	}
	inv[maxn - 1] = power(fact[maxn - 1], mod - 2);
	for (int i = maxn - 2; i >= 0; i--) {
		inv[i] = inv[i + 1] * (i + 1) %mod;
	}
}

3. Linear inversion

So the linear recursion is

inv[i]=(mod-mod/i)*inv[mod%i]%mod;

How to use it? We can use this to find the value of the combined number in the sense of mod, the function is as follows:

const ll mod=1e9+7;
const ll maxn=1e5+1;
 
ll f[maxn]={1,1};
ll f0[maxn]={1,1};
ll inv[maxn]={1,1};
 
void init()
{
    for(int i=2;i<=maxn;i++)
    {
        //阶乘数
        f[i]=f[i-1]*i%mod;
        //i在mod意义下的逆元
        f0[i]=(mod-mod/i)*f0[mod%i]%mod;
        //阶乘逆元
        inv[i]=inv[i-1]*f0[i]%mod;
    }
}
 
//求阶乘数C(a,b)在mod意义下的值
ll C(ll a,ll b)
{    
    return f[b]*inv[a]%mod*inv[b-a]%mod;
}

 

 

Published 660 original articles · praised 562 · 480,000 views

Guess you like

Origin blog.csdn.net/mrcrack/article/details/105219434