Skip to content

Commit 141df23

Browse files
committed
refactor: add NCRModuloP::computeFactorialsMod
1 parent 71234c6 commit 141df23

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

math/ncr_modulo_p.cpp

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,22 +70,34 @@ int64_t modInverse(const uint64_t& a, const uint64_t& m) {
7070
*/
7171
class NCRModuloP {
7272
private:
73-
std::vector<uint64_t> fac{}; /// stores precomputed factorial(i) % p value
74-
uint64_t p = 0; /// the p from (nCr % p)
73+
const uint64_t p; /// the p from (nCr % p)
74+
const std::vector<uint64_t>
75+
fac; /// stores precomputed factorial(i) % p value
76+
77+
/**
78+
* @brief computes the array of values of factorials reduced modulo mod
79+
* @param max_arg_val argument of the last factorial stored in the result
80+
* @param mod value of the divisor used to reduce factorials
81+
* @return vector storing factorials of the numbers 0, ..., max_arg_val
82+
* reduced modulo mod
83+
*/
84+
static std::vector<uint64_t> computeFactorialsMod(
85+
const uint64_t& max_arg_val, const uint64_t& mod) {
86+
auto res = std::vector<uint64_t>(max_arg_val + 1);
87+
res[0] = 1;
88+
for (uint64_t i = 1; i <= max_arg_val; i++) {
89+
res[i] = (res[i - 1] * i) % mod;
90+
}
91+
return res;
92+
}
7593

7694
public:
7795
/** Constructor which precomputes the values of n! % mod from n=0 to size
7896
* and stores them in vector 'fac'
7997
* @params[in] the numbers 'size', 'mod'
8098
*/
81-
NCRModuloP(const uint64_t& size, const uint64_t& mod) {
82-
p = mod;
83-
fac = std::vector<uint64_t>(size + 1);
84-
fac[0] = 1;
85-
for (uint64_t i = 1; i <= size; i++) {
86-
fac[i] = (fac[i - 1] * i) % p;
87-
}
88-
}
99+
NCRModuloP(const uint64_t& size, const uint64_t& mod)
100+
: p(mod), fac(computeFactorialsMod(size, mod)) {}
89101

90102
/** Find nCr % p
91103
*

0 commit comments

Comments
 (0)