47# ifndef MODULAR_COMBINATORICS_H
48# define MODULAR_COMBINATORICS_H
94 <<
"ModularCombinatorics: modulus " <<
mod_ <<
" must be prime";
97 max_n =
static_cast<size_t>(
mod_ - 1);
103 for (
size_t i = 1; i <= max_n; i++)
108 for (
size_t i = max_n; i > 0; i--)
153 std::swap(
mod_, other.mod_);
171 [[nodiscard]] uint64_t
nCk(
const uint64_t n,
const uint64_t
k)
const
175 <<
"ModularCombinatorics::nCk: n=" << n <<
" exceeds precomputed range "
178 const uint64_t num =
fact_[n];
201 [[nodiscard]] uint64_t
lucas_nCk(
const uint64_t n,
const uint64_t
k)
const
204 if (
k == 0)
return 1;
206 const uint64_t ni = n %
mod_;
207 const uint64_t ki =
k %
mod_;
209 if (ki > ni)
return 0;
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void swap(Array &s) noexcept
Swap this with s
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
void putn(const size_t n)
Reserve n additional logical slots in the array without value-initializing them.
High-performance combinatorics operations modulo a prime.
Array< uint64_t > fact_
Precomputed factorials array.
void swap(ModularCombinatorics &other) noexcept
Exchange in O(1) the moduli and the tables of this object and another.
Array< uint64_t > invFact_
Precomputed inverse factorials array.
ModularCombinatorics(const ModularCombinatorics &other)=default
Copy the modulus and the tables of another object.
uint64_t lucas_nCk(const uint64_t n, const uint64_t k) const
Calculate using Lucas' Theorem.
ModularCombinatorics(size_t max_n, const uint64_t p)
Construct and precompute factorials up to 'max_n' modulo 'p'.
ModularCombinatorics & operator=(const ModularCombinatorics &other)=default
Copy the modulus and the tables of another object.
ModularCombinatorics(ModularCombinatorics &&other) noexcept=default
Take the tables of another object, which keeps its modulus and no table: its nCk() throws out_of_rang...
uint64_t mod_
Prime modulus .
uint64_t nCk(const uint64_t n, const uint64_t k) const
Calculate in constant time.
Safe modular arithmetic, extended Euclidean algorithm, and Chinese Remainder Theorem.
Main namespace for Aleph-w library functions.
uint64_t mod_inv(const uint64_t a, const uint64_t m)
Modular Inverse.
bool miller_rabin(uint64_t n) noexcept
Miller-Rabin primality test for 64-bit integers.
uint64_t mod_mul(uint64_t a, uint64_t b, uint64_t m)
Safe 64-bit modular multiplication.
Advanced primality testing algorithms.
Dynamic array container with automatic resizing.