Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
math::ncr_modulo_p::NCRModuloP Class Reference

Class which contains all methods required for calculating nCr mod p. More...

Collaboration diagram for math::ncr_modulo_p::NCRModuloP:
[legend]

Public Member Functions

 NCRModuloP (const int64_t &size, const int64_t &p)
 constructs an NCRModuloP object allowing to compute (nCr)p for inputs from 0 to size
 
int64_t ncr (const int64_t &n, const int64_t &r) const
 computes nCr % p
 

Static Private Member Functions

static std::vector< int64_t > computeFactorialsMod (const int64_t &max_arg_val, const int64_t &mod)
 stores precomputed factorial(i) % p value
 

Private Attributes

const int64_t p = 0
 
const std::vector< int64_t > fac
 the p from (nCr % p)
 

Detailed Description

Class which contains all methods required for calculating nCr mod p.

Constructor & Destructor Documentation

◆ NCRModuloP()

math::ncr_modulo_p::NCRModuloP::NCRModuloP ( const int64_t & size,
const int64_t & p )
inline

constructs an NCRModuloP object allowing to compute (nCr)p for inputs from 0 to size

108 : p(p), fac(computeFactorialsMod(size, p)) {}
const std::vector< int64_t > fac
the p from (nCr % p)
Definition ncr_modulo_p.cpp:83
static std::vector< int64_t > computeFactorialsMod(const int64_t &max_arg_val, const int64_t &mod)
stores precomputed factorial(i) % p value
Definition ncr_modulo_p.cpp:92

Member Function Documentation

◆ computeFactorialsMod()

static std::vector< int64_t > math::ncr_modulo_p::NCRModuloP::computeFactorialsMod ( const int64_t & max_arg_val,
const int64_t & mod )
inlinestaticprivate

stores precomputed factorial(i) % p value

computes the array of values of factorials reduced modulo mod

Parameters
max_arg_valargument of the last factorial stored in the result
modvalue of the divisor used to reduce factorials
Returns
vector storing factorials of the numbers 0, ..., max_arg_val reduced modulo mod
93 {
94 auto res = std::vector<int64_t>(max_arg_val + 1);
95 res[0] = 1;
96 for (int64_t i = 1; i <= max_arg_val; i++) {
97 res[i] = (res[i - 1] * i) % mod;
98 }
99 return res;
100 }

◆ ncr()

int64_t math::ncr_modulo_p::NCRModuloP::ncr ( const int64_t & n,
const int64_t & r ) const
inline

computes nCr % p

Parameters
[in]nthe number of objects to be chosen
[in]rthe number of objects to choose from
Returns
the value nCr % p
116 {
117 // Base cases
118 if (r > n) {
119 return 0;
120 }
121 if (r == 1) {
122 return n % p;
123 }
124 if (r == 0 || r == n) {
125 return 1;
126 }
127 // fac is a global array with fac[r] = (r! % p)
128 const auto denominator = (fac[r] * fac[n - r]) % p;
129 const auto denominator_inv = utils::modInverse(denominator, p);
130 if (denominator_inv < 0) { // modular inverse doesn't exist
131 return -1;
132 }
133 return (fac[n] * denominator_inv) % p;
134 }

The documentation for this class was generated from the following file: