1 /* mpz_bin_uiui - compute n over k.
3 Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2006 Free Software Foundation,
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
26 /* Enhancement: It ought to be possible to calculate the size of the final
27 result in advance, to a rough approximation at least, and use it to do
28 just one realloc. Stirling's approximation n! ~= sqrt(2*pi*n)*(n/e)^n
29 (Knuth section 1.2.5) might be of use. */
31 /* "inc" in the main loop allocates a chunk more space if not already
32 enough, so as to avoid repeated reallocs. The final step on the other
33 hand requires only one more limb. */
36 ASSERT (rsize <= ralloc); \
38 if (rsize == ralloc) \
40 mp_size_t new_ralloc = ralloc + (inc); \
41 rp = __GMP_REALLOCATE_FUNC_LIMBS (rp, ralloc, new_ralloc); \
42 ralloc = new_ralloc; \
45 rp[rsize] = mpn_mul_1 (rp, rp, rsize, nacc); \
46 MPN_DIVREM_OR_DIVEXACT_1 (rp, rp, rsize+1, kacc); \
47 rsize += (rp[rsize] != 0); \
52 mpz_bin_uiui (mpz_ptr r, unsigned long int n, unsigned long int k)
54 unsigned long int i, j;
56 unsigned long int cnt;
57 mp_size_t rsize, ralloc;
60 /* bin(n,k) = 0 if k>n. */
69 /* Rewrite bin(n,k) as bin(n,n-k) if that is smaller. */
85 /* Initialize accumulators. */
89 for (i = 2; i <= k; i++)
93 /* Remove common 2 factors. */
94 cnt = ((nacc | kacc) & 1) ^ 1;
99 /* Accumulate next multiples. */
100 umul_ppmm (n1, n0, nacc, (mp_limb_t) j << GMP_NAIL_BITS);
101 n0 >>= GMP_NAIL_BITS;
104 /* Save new products in accumulators to keep accumulating. */
110 /* Accumulator overflow. Perform bignum step. */
117 /* Take care of whatever is left in accumulators. */