2
Copyright (c) 2007 Thomas Jahns <Thomas.Jahns@gmx.net>
4
Permission to use, copy, modify, and distribute this software for any
5
purpose with or without fee is hereby granted, provided that the above
6
copyright notice and this permission notice appear in all copies.
8
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
#ifndef COMBINATORICS_H
18
#define COMBINATORICS_H
20
#include "core/assert_api.h"
21
#include "core/minmax.h"
24
* \file combinatorics.h
25
* \brief Simple routines for distribution computations relevant to
26
* combinatorial problems.
27
* \author Thomas Jahns <Thomas.Jahns@gmx.net>
31
* Computes \f$n! = 1 \cdot 2 \cdot \dots \cdot (n - 1) \cdot n\f$
32
* @param n number of which to compute factorial
35
static inline unsigned long
45
* \brief Compute binomial coefficient \f[{n\choose k} = \frac{n!}{k!\cdot (n
49
* @return \f$n\choose{k}\f$
51
static inline unsigned long
52
binomialCoeff(unsigned long n, unsigned long k)
59
return binomialCoeff(n, n - k);
66
return accum /= factorial(n - k);
71
* \brief Compute multinomial coefficient
72
* \f[{n\choose k_1, k_2,\dots,k_m} = \frac{n!}{k_1!\cdot
73
* k_2!\cdot\dots\cdot k_m!}\f] where \f$m\f$ equals \link numBins\endlink
76
* @param binSizes points to array containing \link numBins\endlink values which
77
* represent the \f$k_i\f$
78
* @return \f$n\choose{k_1, k_2,\dots,k_m}\f$
80
static inline unsigned long
81
multinomialCoeff(unsigned n, size_t numBins, const unsigned binSizes[])
83
unsigned long accum = 1, nfac;
84
size_t i, maxBin = 0, maxBinSize = 0;
86
unsigned long binSum = 0;
88
gt_assert(n > 0 && numBins > 0 && binSizes);
89
for (i = 0; i < numBins; ++i)
92
binSum += binSizes[i];
94
if (binSizes[i] > maxBinSize)
96
maxBinSize = binSizes[i];
100
gt_assert(binSum <= n);
101
for (nfac = maxBinSize + 1; nfac <= n; ++nfac)
103
for (i = 0; i < numBins; ++i)
105
accum /= factorial(binSizes[i]);
109
static inline unsigned long long
110
iPow(unsigned long long x, unsigned i)
112
unsigned long long result = 1;