Example #1
0
/* Test whether z is likely to be prime:
   MP_TRUE  means it is probably prime
   MP_FALSE means it is definitely composite
 */
mp_result mp_int_is_prime(mp_int z)
{
  int       i, rem;
  mp_result res;

  /* First check for divisibility by small primes; this eliminates a
     large number of composite candidates quickly
   */
  for(i = 0; i < s_ptab_size; ++i) {
    if((res = mp_int_div_value(z, s_ptab[i], NULL, &rem)) != MP_OK)
      return res;

    if(rem == 0)
      return MP_FALSE;
  }

  /* Now try Fermat's test for several prime witnesses (since we now
     know from the above that z is not a multiple of any of them)
   */
  {
    mpz_t  tmp;

    if((res = mp_int_init(&tmp)) != MP_OK) return res;

    for(i = 0; i < 10 && i < s_ptab_size; ++i) {
      if((res = mp_int_exptmod_bvalue(s_ptab[i], z, z, &tmp)) != MP_OK)
	return res;

      if(mp_int_compare_value(&tmp, s_ptab[i]) != 0) {
	mp_int_clear(&tmp);
	return MP_FALSE;
      }
    }

    mp_int_clear(&tmp);
  }

  return MP_TRUE;
}
int test_exptmod_bv(testspec_t *t, FILE *ofp)
{
  mp_int in[4], out[1];
  mp_result res, expect;
  int       v;

  if(!parse_int_values(t, in, out, &expect))
    return imath_errno = MP_BADARG, 0;

  if((res = mp_int_to_int(in[0], &v)) != MP_OK)
    return imath_errno = res, 0;

  if((res = mp_int_exptmod_bvalue(v, in[1], in[2], in[3])) != expect)
    return imath_errno = res, 0;

  if(expect == MP_OK && mp_int_compare(in[3], out[0]) != 0) {
    mp_int_to_string(in[3], 10, g_output, OUTPUT_LIMIT);
    return imath_errno = OTHER_ERROR, 0;
  }

  return 1;
}