jayati

fastest way to calc nCr

Jan 10th, 2024
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // Initial Template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. // } Driver Code Ends
  8. // User function Template for C++
  9.  
  10. class Solution{
  11.  
  12.     const int mod = 1e9+7;
  13.     int binaryexp(int x, int n) {
  14.         if(n == 0) return 1;
  15.         int temp = binaryexp(x, n/2);
  16.         if(n%2 == 0) return (1LL *temp * temp)%mod;
  17.         else return (((1LL*temp*temp)%mod)*x)%mod;
  18.     }
  19.    
  20. public:
  21.     int nCr(int n, int r){
  22.         if(r > n) return 0;
  23.         if(r == n) return 1;
  24.         long long ans = 1;
  25.         //first calculating the numerator
  26.         for(int i = 1; i<=r; i++) {
  27.             ans = (ans*1LL*(i+(n-r)))%mod;
  28.         }
  29.         //now calculating the final ans by dividing the ans with the terms in denominator
  30.         for(int i = 1; i<=r; i++) {
  31.             int inv = binaryexp(i, mod-2);
  32.             ans = ((ans%mod) * (inv%mod))%mod;
  33.         }
  34.         return ans;
  35.     }
  36. };
  37.  
  38. //{ Driver Code Starts.
  39.  
  40. int main(){
  41.     int t;
  42.     cin>>t;
  43.     while(t--){
  44.         int n, r;
  45.         cin>>n>>r;
  46.        
  47.         Solution ob;
  48.         cout<<ob.nCr(n, r)<<endl;
  49.     }
  50.     return 0;
  51. }
  52. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment