1/* mpz_kronecker_ui -- mpz+ulong Kronecker/Jacobi symbol.
2
3Copyright 1999-2002 Free Software Foundation, Inc.
4
5This file is part of the GNU MP Library.
6
7The GNU MP Library is free software; you can redistribute it and/or modify
8it 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
14or
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
20or both in parallel, as here.
21
22The GNU MP Library is distributed in the hope that it will be useful, but
23WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
25for more details.
26
27You should have received copies of the GNU General Public License and the
28GNU Lesser General Public License along with the GNU MP Library.  If not,
29see https://www.gnu.org/licenses/.  */
30
31#include "gmp-impl.h"
32#include "longlong.h"
33
34
35int
36mpz_kronecker_ui (mpz_srcptr a, unsigned long b)
37{
38  mp_srcptr  a_ptr;
39  mp_size_t  a_size;
40  mp_limb_t  a_rem;
41  int        result_bit1;
42
43  a_size = SIZ(a);
44  if (a_size == 0)
45    return JACOBI_0U (b);
46
47  if (b > GMP_NUMB_MAX)
48    {
49      mp_limb_t  blimbs[2];
50      mpz_t      bz;
51      ALLOC(bz) = numberof (blimbs);
52      PTR(bz) = blimbs;
53      mpz_set_ui (bz, b);
54      return mpz_kronecker (a, bz);
55    }
56
57  a_ptr = PTR(a);
58  if ((b & 1) != 0)
59    {
60      result_bit1 = JACOBI_ASGN_SU_BIT1 (a_size, b);
61    }
62  else
63    {
64      mp_limb_t  a_low = a_ptr[0];
65      int        twos;
66
67      if (b == 0)
68	return JACOBI_LS0 (a_low, a_size);   /* (a/0) */
69
70      if (! (a_low & 1))
71	return 0;  /* (even/even)=0 */
72
73      /* (a/2)=(2/a) for a odd */
74      count_trailing_zeros (twos, b);
75      b >>= twos;
76      result_bit1 = (JACOBI_TWOS_U_BIT1 (twos, a_low)
77		     ^ JACOBI_ASGN_SU_BIT1 (a_size, b));
78    }
79
80  if (b == 1)
81    return JACOBI_BIT1_TO_PN (result_bit1);  /* (a/1)=1 for any a */
82
83  a_size = ABS(a_size);
84
85  /* (a/b) = (a mod b / b) */
86  JACOBI_MOD_OR_MODEXACT_1_ODD (result_bit1, a_rem, a_ptr, a_size, b);
87  return mpn_jacobi_base (a_rem, (mp_limb_t) b, result_bit1);
88}
89