2 条题解
-
0xuyifeng LV 10 MOD @ 2017-08-23 15:09:20
Method 1:扩展欧几里得求逆元
-------------------------------------------AC code-------------------------------------------#include<cstdio> #include<iostream> #ifdef WIN32 # define outl "%I64d" #else # define outl "%lld" #endif using namespace std; typedef long long LL; const int MOD = (int)1e9+7; const int N = 1000000; int T, n; LL fac[N<<1+5];//fac --> factorial LL e_gcd(LL a, LL b, LL& x, LL& y){//扩展欧几里得求逆元 if(b == 0){ x = 1, y = 0; return a; } LL ans = e_gcd(b, a%b, x, y); LL t = x; x = y; y = t - (a/b) * y; return ans; } LL cal_inv(LL a, LL m){ LL x, y; LL gcd = e_gcd(a, m, x, y); if(1 % gcd != 0) return -1; x = x * 1 / gcd; if(m < 0) m = -m; LL ans = x % m; if(ans <= 0) ans += m; return ans; } int main(){ scanf("%d", &T); fac[0] = 1; for(int i = 1; i <= 2*N; i++) fac[i] = (fac[i-1] * i) % MOD; while(T--){ scanf("%d", &n); LL a = cal_inv(fac[n]*fac[n], MOD); printf(outl"\n", fac[2*n] * (a%MOD) % MOD);//a / b % c = a * b1 % c(b1是b在模c意义下的逆元) } return 0; }
-
02017-08-23 14:26:06@
Method 2:快速幂求逆元
---------------------------------------------AC code---------------------------------------------#include<cstdio> #ifdef WIN32 # define outl "%I64d" #else # define outl "%lld" #endif using namespace std; typedef long long LL; const int MOD = (int)1e9+7; const int N = 1000000; int T, n; LL fac[N<<1+5]; LL f_pow(LL bs, LL idx, LL mo){ LL ans = 1; bs %= mo; while(idx){ if(idx&1) ans = ans * bs % mo; bs = bs * bs % mo; idx >>= 1; } return ans % mo; } int main(){ scanf("%d", &T); fac[0] = 1; for(int i = 1; i <= (N<<1); i++) fac[i] = (fac[i-1]*i) % MOD; while(T--){ scanf("%d", &n); printf(outl"\n", fac[n<<1] * f_pow(fac[n]*fac[n], MOD-2, MOD) % MOD); } return 0; }
- 1