beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / fac_ui.c
blobe0932272ff6d83c1fa6bbfb6b90a671abbd5f6a9
1 /* mpz_fac_ui(RESULT, N) -- Set RESULT to N!.
3 Contributed to the GNU project by Marco Bodrato.
5 Copyright 1991, 1993-1995, 2000-2003, 2011, 2012 Free Software Foundation, Inc.
7 This file is part of the GNU MP Library.
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free Software
19 Foundation; either version 2 of the License, or (at your option) any
20 later version.
22 or both in parallel, as here.
24 The GNU MP Library is distributed in the hope that it will be useful, but
25 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
26 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 for more details.
29 You should have received copies of the GNU General Public License and the
30 GNU Lesser General Public License along with the GNU MP Library. If not,
31 see https://www.gnu.org/licenses/. */
33 #include "gmp.h"
34 #include "gmp-impl.h"
36 #define FACTOR_LIST_STORE(P, PR, MAX_PR, VEC, I) \
37 do { \
38 if ((PR) > (MAX_PR)) { \
39 (VEC)[(I)++] = (PR); \
40 (PR) = (P); \
41 } else \
42 (PR) *= (P); \
43 } while (0)
45 #if TUNE_PROGRAM_BUILD
46 #define FACTORS_PER_LIMB (GMP_NUMB_BITS / (LOG2C(FAC_DSC_THRESHOLD_LIMIT-1)+1))
47 #else
48 #define FACTORS_PER_LIMB (GMP_NUMB_BITS / (LOG2C(FAC_ODD_THRESHOLD)+1))
49 #endif
51 /* Computes n!, the factorial of n.
52 WARNING: it assumes that n fits in a limb!
54 void
55 mpz_fac_ui (mpz_ptr x, unsigned long n)
57 static const mp_limb_t table[] = { ONE_LIMB_FACTORIAL_TABLE };
59 ASSERT (n <= GMP_NUMB_MAX);
61 if (n < numberof (table))
63 PTR (x)[0] = table[n];
64 SIZ (x) = 1;
66 else if (BELOW_THRESHOLD (n, FAC_ODD_THRESHOLD))
68 mp_limb_t prod, max_prod;
69 mp_size_t j;
70 mp_ptr factors;
71 TMP_SDECL;
73 TMP_SMARK;
74 factors = TMP_SALLOC_LIMBS (2 + (n - numberof (table)) / FACTORS_PER_LIMB);
76 factors[0] = table[numberof (table)-1];
77 j = 1;
78 prod = n;
79 #if TUNE_PROGRAM_BUILD
80 max_prod = GMP_NUMB_MAX / FAC_DSC_THRESHOLD_LIMIT;
81 #else
82 max_prod = GMP_NUMB_MAX / (FAC_ODD_THRESHOLD | 1);
83 #endif
84 while (--n >= numberof (table))
85 FACTOR_LIST_STORE (n, prod, max_prod, factors, j);
87 factors[j++] = prod;
88 mpz_prodlimbs (x, factors, j);
90 TMP_SFREE;
92 else
94 mp_limb_t count;
95 mpz_oddfac_1 (x, n, 0);
96 if (n <= TABLE_LIMIT_2N_MINUS_POPC_2N)
97 count = __gmp_fac2cnt_table[n / 2 - 1];
98 else
100 popc_limb (count, n);
101 count = n - count;
103 mpz_mul_2exp (x, x, count);
107 #undef FACTORS_PER_LIMB
108 #undef FACTOR_LIST_STORE