Advertisement
mhdew

nCr with combinatorics

Apr 4th, 2019
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define ll      long long
  6. #define MOD     1000000007
  7.  
  8. ll bigmod(ll base, ll pw, ll mod)
  9. {
  10.     if(pw==0) return 1%mod;
  11.  
  12.     ll x=bigmod(base,pw/2,mod); //dividing the job into two parts(2^5=2^2&2^2)
  13.  
  14.     x=(x*x)%mod; //combining the divided parts
  15.  
  16.     if(pw%2!=0) x=(x*base)%mod; // if(powe if odd left part is being multiplied)
  17.  
  18.     return x;
  19. }
  20.  
  21. ll mFact[11111111];
  22. void modFact(ll modval)
  23. {  
  24.     mFact[0]=1;
  25.     for(int i=1;i<=10000000;i++){
  26.         mFact[i]=(((mFact[i-1]%modval)*(i%modval))%modval);
  27.     }
  28. }
  29.  
  30. ll invmod(ll y, ll x, ll modval)
  31. {
  32.     ll down=bigmod(x,modval-2,modval);
  33.  
  34.     return ((y%modval)*(down%modval))%modval;
  35. }
  36.  
  37. ll nCr(ll n, ll r, ll modval)
  38. {
  39.     // cout<<n<<" "<<mFact[n]<<endl;
  40.     // cout<<r<<" "<<mFact[r]<<endl;
  41.     // cout<<n-r<<" "<<mFact[n-r]<<endl;
  42.     ll rv=((mFact[n]%modval)*((bigmod(mFact[r],modval-2,modval))%modval)*((bigmod(mFact[n-r],modval-2,modval)%modval)))%modval;
  43.  
  44.     return rv;
  45. }
  46.  
  47. ll nCr2(ll n, ll r, ll modval)
  48. {
  49.     ll rv=1;
  50.     ll x=r, y=n-r;
  51.     ll total=1;
  52.     if(x<y) swap(x,y);
  53.     for(ll i=n;i>x;i--){
  54.         total=((total%modval)*(i%modval))%modval;
  55.     }
  56.  
  57.     return invmod(total,y,modval);
  58. }
  59.  
  60. int main()
  61. {
  62.     //in1();
  63.     //out1();  
  64.     clock_t tStart = clock();
  65.  
  66.     modFact(MOD);
  67.     cout<<nCr(10,3,MOD)<<endl;
  68.     cout<<nCr2(10,3,MOD)<<endl;
  69.  
  70.     printf("\n>>Runtime: %.10fs\n", (double) (clock() - tStart) / CLOCKS_PER_SEC);
  71.  
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement