xref: /dragonfly/contrib/gmp/mpz/kronzs.c (revision 0db87cb7)
1 /* mpz_kronecker_si -- mpz+long Kronecker/Jacobi symbol.
2 
3 Copyright 1999, 2000, 2001, 2002 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 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.
11 
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.
16 
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/.  */
19 
20 #include "gmp.h"
21 #include "gmp-impl.h"
22 #include "longlong.h"
23 
24 
25 /* After the absolute value of b is established it's treated as an unsigned
26    long, because 0x80..00 doesn't fit in a signed long. */
27 
28 int
29 mpz_kronecker_si (mpz_srcptr a, long b)
30 {
31   mp_srcptr  a_ptr;
32   mp_size_t  a_size;
33   mp_limb_t  a_rem, b_limb;
34   int        result_bit1;
35 
36   a_size = SIZ(a);
37   if (a_size == 0)
38     return JACOBI_0S (b);
39 
40 #if GMP_NUMB_BITS < BITS_PER_ULONG
41   if (b > GMP_NUMB_MAX || b < -GMP_NUMB_MAX)
42     {
43       mp_limb_t  blimbs[2];
44       mpz_t      bz;
45       ALLOC(bz) = numberof (blimbs);
46       PTR(bz) = blimbs;
47       mpz_set_si (bz, b);
48       return mpz_kronecker (a, bz);
49     }
50 #endif
51 
52   result_bit1 = JACOBI_BSGN_SS_BIT1 (a_size, b);
53   b_limb = (unsigned long) ABS (b);
54   a_ptr = PTR(a);
55 
56   if ((b_limb & 1) == 0)
57     {
58       mp_limb_t  a_low = a_ptr[0];
59       int        twos;
60 
61       if (b_limb == 0)
62         return JACOBI_LS0 (a_low, a_size);   /* (a/0) */
63 
64       if (! (a_low & 1))
65         return 0;  /* (even/even)=0 */
66 
67       /* (a/2)=(2/a) for a odd */
68       count_trailing_zeros (twos, b_limb);
69       b_limb >>= twos;
70       result_bit1 ^= JACOBI_TWOS_U_BIT1 (twos, a_low);
71     }
72 
73   if (b_limb == 1)
74     return JACOBI_BIT1_TO_PN (result_bit1);  /* (a/1)=1 for any a */
75 
76   result_bit1 ^= JACOBI_ASGN_SU_BIT1 (a_size, b_limb);
77   a_size = ABS(a_size);
78 
79   /* (a/b) = (a mod b / b) */
80   JACOBI_MOD_OR_MODEXACT_1_ODD (result_bit1, a_rem, a_ptr, a_size, b_limb);
81   return mpn_jacobi_base (a_rem, b_limb, result_bit1);
82 }
83