int aws_mp_jacobi()

in AWSCognitoIdentityProvider/Internal/JKBigInteger/LibTomMath/tommath.c [2449:2530]


int aws_mp_jacobi(aws_mp_int *a, aws_mp_int *p, int *c)
{
  aws_mp_int a1, p1;
  int     k, s, r, res;
  aws_mp_digit residue;

  /* if p <= 0 return AWS_MP_VAL */
  if (aws_mp_cmp_d(p, 0) != AWS_MP_GT) {
     return AWS_MP_VAL;
  }

  /* step 1.  if a == 0, return 0 */
  if (aws_mp_iszero (a) == 1) {
    *c = 0;
    return AWS_MP_OKAY;
  }

  /* step 2.  if a == 1, return 1 */
  if (aws_mp_cmp_d(a, 1) == AWS_MP_EQ) {
    *c = 1;
    return AWS_MP_OKAY;
  }

  /* default */
  s = 0;

  /* step 3.  write a = a1 * 2**k  */
  if ((res = aws_mp_init_copy(&a1, a)) != AWS_MP_OKAY) {
    return res;
  }

  if ((res = aws_mp_init(&p1)) != AWS_MP_OKAY) {
    goto LBL_A1;
  }

  /* divide out larger power of two */
  k = aws_mp_cnt_lsb(&a1);
  if ((res = aws_mp_div_2d(&a1, k, &a1, NULL)) != AWS_MP_OKAY) {
     goto LBL_P1;
  }

  /* step 4.  if e is even set s=1 */
  if ((k & 1) == 0) {
    s = 1;
  } else {
    /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */
    residue = p->dp[0] & 7;

    if (residue == 1 || residue == 7) {
      s = 1;
    } else if (residue == 3 || residue == 5) {
      s = -1;
    }
  }

  /* step 5.  if p == 3 (mod 4) *and* a1 == 3 (mod 4) then s = -s */
  if (((p->dp[0] & 3) == 3) && ((a1.dp[0] & 3) == 3)) {
    s = -s;
  }

  /* if a1 == 1 we're done */
  if (aws_mp_cmp_d(&a1, 1) == AWS_MP_EQ) {
    *c = s;
  } else {
    /* n1 = n mod a1 */
    if ((res = aws_mp_mod(p, &a1, &p1)) != AWS_MP_OKAY) {
      goto LBL_P1;
    }
    if ((res = aws_mp_jacobi(&p1, &a1, &r)) != AWS_MP_OKAY) {
      goto LBL_P1;
    }
    *c = s * r;
  }

  /* done */
  res = AWS_MP_OKAY;
LBL_P1:
aws_mp_clear(&p1);
LBL_A1:
aws_mp_clear(&a1);
  return res;
}