1 /* mpz_2fac_ui(RESULT, N) -- Set RESULT to N!!. 2 3 Contributed to the GNU project by Marco Bodrato. 4 5 Copyright 2012 Free Software Foundation, Inc. 6 7 This file is part of the GNU MP Library. 8 9 The GNU MP Library is free software; you can redistribute it and/or modify 10 it under the terms of the GNU Lesser General Public License as published by 11 the Free Software Foundation; either version 3 of the License, or (at your 12 option) any later version. 13 14 The GNU MP Library is distributed in the hope that it will be useful, but 15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 17 License for more details. 18 19 You should have received a copy of the GNU Lesser General Public License 20 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 21 22 #include "gmp.h" 23 #include "gmp-impl.h" 24 25 #define FACTOR_LIST_STORE(P, PR, MAX_PR, VEC, I) \ 26 do { \ 27 if ((PR) > (MAX_PR)) { \ 28 (VEC)[(I)++] = (PR); \ 29 (PR) = (P); \ 30 } else \ 31 (PR) *= (P); \ 32 } while (0) 33 34 #define FAC_2DSC_THRESHOLD ((FAC_DSC_THRESHOLD << 1) | (FAC_DSC_THRESHOLD & 1)) 35 #define FACTORS_PER_LIMB (GMP_NUMB_BITS / (LOG2C(FAC_2DSC_THRESHOLD-1)+1)) 36 37 /* Computes n!!, the 2-multi-factorial of n. (aka double-factorial or semi-factorial) 38 WARNING: it assumes that n fits in a limb! 39 */ 40 void 41 mpz_2fac_ui (mpz_ptr x, unsigned long n) 42 { 43 ASSERT (n <= GMP_NUMB_MAX); 44 45 if ((n & 1) == 0) { /* n is even, n = 2k, (2k)!! = k! 2^k */ 46 mp_limb_t count; 47 48 if ((n <= TABLE_LIMIT_2N_MINUS_POPC_2N) & (n != 0)) 49 count = __gmp_fac2cnt_table[n / 2 - 1]; 50 else 51 { 52 popc_limb (count, n); /* popc(n) == popc(k) */ 53 count = n - count; /* n - popc(n) == k + k - popc(k) */ 54 } 55 mpz_oddfac_1 (x, n >> 1, 0); 56 mpz_mul_2exp (x, x, count); 57 } else { /* n is odd */ 58 if (n <= ODD_DOUBLEFACTORIAL_TABLE_LIMIT) { 59 PTR (x)[0] = __gmp_odd2fac_table[n >> 1]; 60 SIZ (x) = 1; 61 } else if (BELOW_THRESHOLD (n, FAC_2DSC_THRESHOLD)) { /* odd basecase, */ 62 mp_limb_t *factors, prod, max_prod, j; 63 TMP_SDECL; 64 65 /* FIXME: we might alloc a fixed ammount 1+FAC_2DSC_THRESHOLD/FACTORS_PER_LIMB */ 66 TMP_SMARK; 67 factors = TMP_SALLOC_LIMBS (1 + n / (2 * FACTORS_PER_LIMB)); 68 69 factors[0] = ODD_DOUBLEFACTORIAL_TABLE_MAX; 70 j = 1; 71 prod = n; 72 73 max_prod = GMP_NUMB_MAX / FAC_2DSC_THRESHOLD; 74 while ((n -= 2) > ODD_DOUBLEFACTORIAL_TABLE_LIMIT) 75 FACTOR_LIST_STORE (n, prod, max_prod, factors, j); 76 77 factors[j++] = prod; 78 mpz_prodlimbs (x, factors, j); 79 80 TMP_SFREE; 81 } else { /* for the asymptotically fast odd case, let oddfac do the job. */ 82 mpz_oddfac_1 (x, n, 1); 83 } 84 } 85 } 86 87 #undef FACTORS_PER_LIMB 88 #undef FACTOR_LIST_STORE 89 #undef FAC_2DSC_THRESHOLD 90