Advertisement
MinhNGUYEN2k4

nCr

May 23rd, 2021
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. /*
  2. Tính nCr trong O(N) với mod P nguyên tố.
  3.  
  4. Ta sử dụng công thức nCr = n! / r! / (n-r)!
  5.  
  6. Khởi tạo trước fac[i] = i! mod P
  7. Khởi tạo trước ifac[i] = i!^-1 mod P (nghịch đảo modulo P của i!).
  8.  
  9. Từ đó dễ dàng tính được nCr trong O(1).
  10. */
  11. //by Tanmay Chaudhari
  12. #include <bits/stdc++.h>
  13. using namespace std;
  14.  
  15. const int MOD = 1e9 + 7;
  16. #define N 2123456
  17. #define LL long long
  18.  
  19. LL fac[N], ifac[N];
  20.  
  21. LL PowerMod(LL a, LL n){
  22.     LL ret = 1;
  23.     while (n){
  24.         if (n & 1){
  25.             ret *= a;
  26.             ret %= MOD;
  27.         }
  28.         a *= a;
  29.         a %= MOD;
  30.         n /= 2;
  31.     }
  32.     return ret;
  33. }
  34.  
  35. inline void precompute(){
  36.     int i;
  37.     fac[0] = 1;
  38.     for (i = 1; i < N; i++){
  39.         fac[i] = (i * fac[i - 1]) % MOD;
  40.     }
  41.     ifac[N - 1] = PowerMod(fac[N - 1], MOD - 2);
  42.     for (i = N - 2; i >= 0; i--){
  43.         ifac[i] = ((i + 1) * ifac[i + 1]) % MOD;
  44.     }
  45. }
  46.  
  47. LL com(int n, int r){
  48.     LL ret = fac[n];
  49.     ret *= ifac[r];
  50.     ret %= MOD;
  51.     ret *= ifac[n - r];
  52.     ret %= MOD;
  53.     return ret;
  54. }
  55.  
  56. int main()
  57. {
  58.     precompute();
  59.     cout << com(4892,231) << endl;
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement