int aws_mp_is_square()

in AWSCognitoIdentityProvider/Internal/JKBigInteger/LibTomMath/tommath.c [6658:6722]


int aws_mp_is_square(aws_mp_int *arg, int *ret)
{
  int           res;
  aws_mp_digit      c;
  aws_mp_int t;
  unsigned long r;

  /* Default to Non-square :) */
  *ret = AWS_MP_NO;

  if (arg->sign == AWS_MP_NEG) {
    return AWS_MP_VAL;
  }

  /* digits used?  (TSD) */
  if (arg->used == 0) {
     return AWS_MP_OKAY;
  }

  /* First check mod 128 (suppose that AWS_DIGIT_BIT is at least 7) */
  if (rem_128[127 & AWS_JKTM_DIGIT(arg,0)] == 1) {
     return AWS_MP_OKAY;
  }

  /* Next check mod 105 (3*5*7) */
  if ((res = aws_mp_mod_d(arg, 105, &c)) != AWS_MP_OKAY) {
     return res;
  }
  if (rem_105[c] == 1) {
     return AWS_MP_OKAY;
  }


  if ((res = aws_mp_init_set_int(&t, 11L * 13L * 17L * 19L * 23L * 29L * 31L)) != AWS_MP_OKAY) {
     return res;
  }
  if ((res = aws_mp_mod(arg, &t, &t)) != AWS_MP_OKAY) {
     goto ERR;
  }
  r = aws_mp_get_int(&t);
  /* Check for other prime modules, note it's not an ERROR but we must
   * free "t" so the easiest way is to goto ERR.  We know that res
   * is already equal to AWS_MP_OKAY from the aws_mp_mod call
   */ 
  if ( (1L<<(r%11)) & 0x5C4L )             goto ERR;
  if ( (1L<<(r%13)) & 0x9E4L )             goto ERR;
  if ( (1L<<(r%17)) & 0x5CE8L )            goto ERR;
  if ( (1L<<(r%19)) & 0x4F50CL )           goto ERR;
  if ( (1L<<(r%23)) & 0x7ACCA0L )          goto ERR;
  if ( (1L<<(r%29)) & 0xC2EDD0CL )         goto ERR;
  if ( (1L<<(r%31)) & 0x6DE2B848L )        goto ERR;

  /* Final check - is sqr(sqrt(arg)) == arg ? */
  if ((res = aws_mp_sqrt(arg, &t)) != AWS_MP_OKAY) {
     goto ERR;
  }
  if ((res = aws_mp_sqr(&t, &t)) != AWS_MP_OKAY) {
     goto ERR;
  }

  *ret = (aws_mp_cmp_mag(&t, arg) == AWS_MP_EQ) ? AWS_MP_YES : AWS_MP_NO;
ERR:
aws_mp_clear(&t);
  return res;
}