github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/mpz/lucnum2_ui.c (about) 1 /* mpz_lucnum2_ui -- calculate Lucas numbers. 2 3 Copyright 2001, 2003, 2005, 2012 Free Software Foundation, Inc. 4 5 This file is part of the GNU MP Library. 6 7 The GNU MP Library is free software; you can redistribute it and/or modify 8 it under the terms of either: 9 10 * the GNU Lesser General Public License as published by the Free 11 Software Foundation; either version 3 of the License, or (at your 12 option) any later version. 13 14 or 15 16 * the GNU General Public License as published by the Free Software 17 Foundation; either version 2 of the License, or (at your option) any 18 later version. 19 20 or both in parallel, as here. 21 22 The GNU MP Library is distributed in the hope that it will be useful, but 23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 25 for more details. 26 27 You should have received copies of the GNU General Public License and the 28 GNU Lesser General Public License along with the GNU MP Library. If not, 29 see https://www.gnu.org/licenses/. */ 30 31 #include <stdio.h> 32 #include "gmp.h" 33 #include "gmp-impl.h" 34 35 36 void 37 mpz_lucnum2_ui (mpz_ptr ln, mpz_ptr lnsub1, unsigned long n) 38 { 39 mp_ptr lp, l1p, f1p; 40 mp_size_t size; 41 mp_limb_t c; 42 TMP_DECL; 43 44 ASSERT (ln != lnsub1); 45 46 /* handle small n quickly, and hide the special case for L[-1]=-1 */ 47 if (n <= FIB_TABLE_LUCNUM_LIMIT) 48 { 49 mp_limb_t f = FIB_TABLE (n); 50 mp_limb_t f1 = FIB_TABLE ((int) n - 1); 51 52 /* L[n] = F[n] + 2F[n-1] */ 53 PTR(ln)[0] = f + 2*f1; 54 SIZ(ln) = 1; 55 56 /* L[n-1] = 2F[n] - F[n-1], but allow for L[-1]=-1 */ 57 PTR(lnsub1)[0] = (n == 0 ? 1 : 2*f - f1); 58 SIZ(lnsub1) = (n == 0 ? -1 : 1); 59 60 return; 61 } 62 63 TMP_MARK; 64 size = MPN_FIB2_SIZE (n); 65 f1p = TMP_ALLOC_LIMBS (size); 66 67 lp = MPZ_REALLOC (ln, size+1); 68 l1p = MPZ_REALLOC (lnsub1, size+1); 69 70 size = mpn_fib2_ui (l1p, f1p, n); 71 72 /* L[n] = F[n] + 2F[n-1] */ 73 #if HAVE_NATIVE_mpn_addlsh1_n 74 c = mpn_addlsh1_n (lp, l1p, f1p, size); 75 #else 76 c = mpn_lshift (lp, f1p, size, 1); 77 c += mpn_add_n (lp, lp, l1p, size); 78 #endif 79 lp[size] = c; 80 SIZ(ln) = size + (c != 0); 81 82 /* L[n-1] = 2F[n] - F[n-1] */ 83 c = mpn_lshift (l1p, l1p, size, 1); 84 c -= mpn_sub_n (l1p, l1p, f1p, size); 85 ASSERT ((mp_limb_signed_t) c >= 0); 86 l1p[size] = c; 87 SIZ(lnsub1) = size + (c != 0); 88 89 TMP_FREE; 90 }