bhupixb

nCr optimized

May 7th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MOD = 1e9 + 7;
  5. const int N = 2000012;
  6. long long fact[N], invFact[N];
  7.  
  8. void pre(){
  9.  
  10. fact[0] = invFact[0] = invFact[1] = 1;
  11.  
  12. for(int i = 1 ; i < N ; i++)
  13. fact[i] = (fact[i-1] * i) % MOD;
  14.  
  15. for(int i = 2 ; i < N ; i++)
  16. invFact[i] = (MOD - MOD / i) * invFact[MOD % i] % MOD;
  17.  
  18. for(int i = 1; i < N ; i++)
  19. invFact[i] = (invFact[i-1] * invFact[i]) % MOD;
  20.  
  21. }
  22. long long nCr(long long n, long long r){
  23. return ((( fact[n] * invFact[r] ) % MOD) * invFact[n-r]) % MOD;
  24. }
  25. int main()
  26. {
  27. pre();
  28. long long t,n,k;
  29. scanf("%lld",&t);
  30. while(t--) {
  31. scanf("%lld%lld",&n,&k);
  32. printf("%lld\n",(nCr(n,k)));
  33. }
  34. return 0;
  35. }
Add Comment
Please, Sign In to add comment