1 /* mpz_lucnum2_ui -- calculate Lucas numbers.
3 Copyright 2001, 2003, 2005 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
26 mpz_lucnum2_ui (mpz_ptr ln, mpz_ptr lnsub1, unsigned long n)
33 ASSERT (ln != lnsub1);
35 /* handle small n quickly, and hide the special case for L[-1]=-1 */
36 if (n <= FIB_TABLE_LUCNUM_LIMIT)
38 mp_limb_t f = FIB_TABLE (n);
39 mp_limb_t f1 = FIB_TABLE ((int) n - 1);
41 /* L[n] = F[n] + 2F[n-1] */
42 PTR(ln)[0] = f + 2*f1;
45 /* L[n-1] = 2F[n] - F[n-1], but allow for L[-1]=-1 */
46 PTR(lnsub1)[0] = (n == 0 ? 1 : 2*f - f1);
47 SIZ(lnsub1) = (n == 0 ? -1 : 1);
53 size = MPN_FIB2_SIZE (n);
54 f1p = TMP_ALLOC_LIMBS (size);
56 MPZ_REALLOC (ln, size+1);
57 MPZ_REALLOC (lnsub1, size+1);
61 size = mpn_fib2_ui (l1p, f1p, n);
63 /* L[n] = F[n] + 2F[n-1] */
64 #if HAVE_NATIVE_mpn_addlsh1_n
65 c = mpn_addlsh1_n (lp, l1p, f1p, size);
67 c = mpn_lshift (lp, f1p, size, 1);
68 c += mpn_add_n (lp, lp, l1p, size);
71 SIZ(ln) = size + (c != 0);
73 /* L[n-1] = 2F[n] - F[n-1] */
74 c = mpn_lshift (l1p, l1p, size, 1);
75 c -= mpn_sub_n (l1p, l1p, f1p, size);
76 ASSERT ((mp_limb_signed_t) c >= 0);
78 SIZ(lnsub1) = size + (c != 0);