Beispiel #1
0
ecl_uint64_t
ecl_to_uint64_t(cl_object x) {
	if (!ecl_minusp(x)) {
		if (ECL_FIXNUMP(x)) {
			return (ecl_uint64_t)ecl_fixnum(x);
		} else if (!ECL_BIGNUMP(x)) {
			(void)0;
		} else if (mpz_fits_ulong_p(x->big.big_num)) {
			return (ecl_uint64_t)mpz_get_ui(x->big.big_num);
		} else {
			cl_object copy = _ecl_big_register0();
			mpz_fdiv_q_2exp(copy->big.big_num, x->big.big_num, 32);
			if (mpz_fits_ulong_p(copy->big.big_num)) {
				volatile ecl_uint64_t output;
				output = (ecl_uint64_t)mpz_get_ui(copy->big.big_num);
				output = (output << 32) +
					(ecl_uint64_t)mpz_get_ui(x->big.big_num);
				return output;
			}
		}
	}
	FEwrong_type_argument(cl_list(3,ECL_SYM("INTEGER",437),ecl_make_fixnum(0),
				      ecl_one_minus(ecl_ash(ecl_make_fixnum(1), 64))),
			      x);
}
Beispiel #2
0
ecl_ulong_long_t
ecl_to_ulong_long(cl_object x) {
	if (!ecl_minusp(x)) {
		if (ECL_FIXNUMP(x)) {
			return (ecl_ulong_long_t)ecl_fixnum(x);
		} else if (!ECL_BIGNUMP(x)) {
			(void)0;
		} else if (mpz_fits_ulong_p(x->big.big_num)) {
			return (ecl_ulong_long_t)mpz_get_ui(x->big.big_num);
		} else {
			cl_object copy = _ecl_big_register0();
			int i = ECL_LONG_LONG_BITS - FIXNUM_BITS;
			mpz_fdiv_q_2exp(copy->bit.big_num, x->big.big_num, i);
			if (mpz_fits_ulong_p(copy->big.big_num)) {
				volatile ecl_ulong_long_t output;
				output = mpz_get_ui(copy->big.big_num);
				for (i -= FIXNUM_BITS; i; i-= FIXNUM_BITS) {
					output = (output << FIXNUM_BITS);
					output += mpz_get_ui(x->big.big_num);
				}
				return output;
			}
		}
	}
	FEwrong_type_argument(cl_list(3,ECL_SYM("INTEGER",437),ecl_make_fixnum(0),
				      ecl_one_minus(ecl_ash(ecl_make_fixnum(1),
							    ECL_LONG_LONG_BITS))),
			      x);
}
Beispiel #3
0
void
check_all (mpz_ptr w, mpz_ptr x, mpz_ptr y)
{
  int    swap, wneg, xneg, yneg;

  MPZ_CHECK_FORMAT (w);
  MPZ_CHECK_FORMAT (x);
  MPZ_CHECK_FORMAT (y);

  for (swap = 0; swap < 2; swap++)
    {
      for (wneg = 0; wneg < 2; wneg++)
        {
          for (xneg = 0; xneg < 2; xneg++)
            {
              for (yneg = 0; yneg < 2; yneg++)
                {
                  check_one (w, x, y);

                  if (mpz_fits_ulong_p (y))
                    check_one_ui (w, x, mpz_get_ui (y));

                  mpz_neg (y, y);
                }
              mpz_neg (x, x);
            }
          mpz_neg (w, w);
        }
      mpz_swap (x, y);
    }
}
Beispiel #4
0
/* Called when s is supposed to be floor(root(u,z)), and r = u - s^z */
static int
rootrem_valid_p (const mpz_t u, const mpz_t s, const mpz_t r, unsigned long z)
{
  mpz_t t;

  mpz_init (t);
  if (mpz_fits_ulong_p (s))
    mpz_ui_pow_ui (t, mpz_get_ui (s), z);
  else
    mpz_pow_ui (t, s, z);
  mpz_sub (t, u, t);
  if (mpz_sgn (t) != mpz_sgn(u) || mpz_cmp (t, r) != 0)
    {
      mpz_clear (t);
      return 0;
    }
  if (mpz_sgn (s) > 0)
    mpz_add_ui (t, s, 1);
  else
    mpz_sub_ui (t, s, 1);
  mpz_pow_ui (t, t, z);
  if (mpz_cmpabs (t, u) <= 0)
    {
      mpz_clear (t);
      return 0;
    }

  mpz_clear (t);
  return 1;
}
Beispiel #5
0
void
check_one (mpz_srcptr a, mpz_srcptr d, int want)
{
  int   got;

  if (mpz_fits_ulong_p (d))
    {
      unsigned long  u = mpz_get_ui (d);
      got = (mpz_divisible_ui_p (a, u) != 0);
      if (want != got)
        {
          printf ("mpz_divisible_ui_p wrong\n");
          printf ("   expected %d got %d\n", want, got);
          mpz_trace ("   a", a);
          printf ("   d=%lu\n", u);
          mp_trace_base = -16;
          mpz_trace ("   a", a);
          printf ("   d=0x%lX\n", u);
          abort ();
        }
    }

  got = (mpz_divisible_p (a, d) != 0);
  if (want != got)
    {
      printf ("mpz_divisible_p wrong\n");
      printf ("   expected %d got %d\n", want, got);
      mpz_trace ("   a", a);
      mpz_trace ("   d", d);
      mp_trace_base = -16;
      mpz_trace ("   a", a);
      mpz_trace ("   d", d);
      abort ();
    }
}
Beispiel #6
0
inline unsigned int check_ub32(Value value)
{
#ifdef __x86_64__
  if (fixnump(value))
    {
      long n = xlong(value);
      if (n >= 0 && n < 4294967296)
        return (unsigned int) n;
    }
#else
  // 32-bit Lisp
  if (fixnump(value))
    {
      long n = xlong(value);
      if (n >= 0)
        return (unsigned int) n;
    }
  else if (bignump(value))
    {
      Bignum * b = the_bignum(value);
      if (mpz_sgn(b->_z) >= 0 && mpz_fits_ulong_p(b->_z))
        return mpz_get_ui(b->_z);
    }
#endif
  signal_type_error(value, UB32_TYPE);
  // not reached
  return 0;
}
Beispiel #7
0
num_t
num_int_one_op(optype_t op_type, num_t a)
{
	num_t r;

	r = num_new_z(N_TEMP, NULL);
	a = num_new_z(N_TEMP, a);

	switch (op_type) {
	case OP_UINV:
		mpz_com(Z(r), Z(a));
		break;

	case OP_FAC:
		if (!mpz_fits_ulong_p(Z(a))) {
			yyxerror
			    ("Argument to factorial needs to fit into an unsigned long C datatype");
			return NULL;
		}
		mpz_fac_ui(Z(r), mpz_get_ui(Z(a)));
		break;

	default:
		yyxerror("Unknown op in num_int_one_op");
	}

	return r;
}
Beispiel #8
0
num_t
num_int_two_op(optype_t op_type, num_t a, num_t b)
{
	num_t r;

	r = num_new_z(N_TEMP, NULL);
	a = num_new_z(N_TEMP, a);
	b = num_new_z(N_TEMP, b);

	switch (op_type) {
	case OP_AND:
		mpz_and(Z(r), Z(a), Z(b));
		break;

	case OP_OR:
		mpz_ior(Z(r), Z(a), Z(b));
		break;

	case OP_XOR:
		mpz_xor(Z(r), Z(a), Z(b));
		break;

	case OP_SHR:
		if (!mpz_fits_ulong_p(Z(b))) {
			yyxerror
			    ("Second argument to shift needs to fit into an unsigned long C datatype");
			return NULL;
		}
		mpz_fdiv_q_2exp(Z(r), Z(a), mpz_get_ui(Z(b)));
		break;

	case OP_SHL:
		if (!mpz_fits_ulong_p(Z(b))) {
			yyxerror
			    ("Second argument to shift needs to fit into an unsigned long C datatype");
			return NULL;
		}
		mpz_mul_2exp(Z(r), Z(a), mpz_get_ui(Z(b)));
		break;

	default:
		yyxerror("Unknown op in num_int_two_op");
	}

	return r;
}
Beispiel #9
0
void
check_one (mpz_srcptr a, mpz_srcptr c, mpz_srcptr d, int want)
{
  int   got;
  int   swap;

  for (swap = 0; swap <= 1; swap++)
    {
      got = (mpz_congruent_p (a, c, d) != 0);
      if (want != got)
        {
          printf ("mpz_congruent_p wrong\n");
          printf ("   expected %d got %d\n", want, got);
          mpz_trace ("   a", a);
          mpz_trace ("   c", c);
          mpz_trace ("   d", d);
          mp_trace_base = -16;
          mpz_trace ("   a", a);
          mpz_trace ("   c", c);
          mpz_trace ("   d", d);
          abort ();
        }

      if (mpz_fits_ulong_p (c) && mpz_fits_ulong_p (d))
        {
          unsigned long  uc = mpz_get_ui (c);
          unsigned long  ud = mpz_get_ui (d);
          got = (mpz_congruent_ui_p (a, uc, ud) != 0);
          if (want != got)
            {
              printf    ("mpz_congruent_ui_p wrong\n");
              printf    ("   expected %d got %d\n", want, got);
              mpz_trace ("   a", a);
              printf    ("   c=%lu\n", uc);
              printf    ("   d=%lu\n", ud);
              mp_trace_base = -16;
              mpz_trace ("   a", a);
              printf    ("   c=0x%lX\n", uc);
              printf    ("   d=0x%lX\n", ud);
              abort ();
            }
        }

      MPZ_SRCPTR_SWAP (a, c);
    }
}
Beispiel #10
0
void
testmain (int argc, char **argv)
{
  unsigned i;
  mpz_t a, b, res, ref;

  mpz_init (a);
  mpz_init (b);
  mpz_init_set_ui (res, 5);
  mpz_init (ref);

  for (i = 0; i < COUNT; i++)
    {
      mini_random_op3 (OP_MUL, MAXBITS, a, b, ref);
      if (i & 1) {
	mpz_add (ref, ref, res);
	if (mpz_fits_ulong_p (b))
	  mpz_addmul_ui (res, a, mpz_get_ui (b));
	else
	  mpz_addmul (res, a, b);
      } else {
	mpz_sub (ref, res, ref);
	if (mpz_fits_ulong_p (b))
	  mpz_submul_ui (res, a, mpz_get_ui (b));
	else
	  mpz_submul (res, a, b);
      }
      if (mpz_cmp (res, ref))
	{
	  if (i & 1)
	    fprintf (stderr, "mpz_addmul failed:\n");
	  else
	    fprintf (stderr, "mpz_submul failed:\n");
	  dump ("a", a);
	  dump ("b", b);
	  dump ("r", res);
	  dump ("ref", ref);
	  abort ();
	}
    }
  mpz_clear (a);
  mpz_clear (b);
  mpz_clear (res);
  mpz_clear (ref);
}
Beispiel #11
0
unsigned long to_ulong(obj_t *o) {
    mpz_t *x = to_mpz(o);
    unsigned int r = 0;
    if (mpz_fits_ulong_p(*x)) {
        r = mpz_get_ui(*x);
    } else {
        error("Argument too big.\n");
    }
    return r;
}
Beispiel #12
0
static uint64_t asUnsignedLong(BoxedLong* self) {
    assert(self->cls == long_cls);

    if (mpz_sgn(self->n) == -1)
        raiseExcHelper(OverflowError, "can't convert negative value to unsigned long");

    if (!mpz_fits_ulong_p(self->n))
        raiseExcHelper(OverflowError, "long int too large to convert");
    return mpz_get_ui(self->n);
}
Beispiel #13
0
void field_init_fp(field_ptr f, mpz_t modulus) {
  if (mpz_fits_ulong_p(modulus)) {
    // If this case mattered, I'd have written a F_p implementation specialized
    // for moduli that fits into machine words.
    field_init_naive_fp(f, modulus);
  } else {
    if (mpz_odd_p(modulus)) {
      option_fpinit(f, modulus);
    } else {
      // montfp.c only supports odd moduli.
      field_init_faster_fp(f, modulus);
    }
  }
}
Beispiel #14
0
void
check_one (mpz_srcptr want, mpz_srcptr base, unsigned long exp)
{
  mpz_t  got;

  mpz_init (got);

  MPZ_CHECK_FORMAT (want);

  mpz_pow_ui (got, base, exp);
  if (mpz_cmp (got, want))
    {
      printf ("mpz_pow_ui wrong\n");
      mpz_trace ("  base", base);
      printf    ("  exp = %lu (0x%lX)\n", exp, exp);
      mpz_trace ("  got ", got);
      mpz_trace ("  want", want);
      abort ();
    }

  mpz_set (got, base);
  mpz_pow_ui (got, got, exp);
  if (mpz_cmp (got, want))
    {
      printf ("mpz_pow_ui wrong\n");
      mpz_trace ("  base", base);
      printf    ("  exp = %lu (0x%lX)\n", exp, exp);
      mpz_trace ("  got ", got);
      mpz_trace ("  want", want);
      abort ();
    }

  if (mpz_fits_ulong_p (base))
    {
      unsigned long  base_u = mpz_get_ui (base);
      mpz_ui_pow_ui (got, base_u, exp);
      if (mpz_cmp (got, want))
	{
	  printf    ("mpz_ui_pow_ui wrong\n");
	  printf    ("  base=%lu (0x%lX)\n", base_u, base_u);
	  printf    ("  exp = %lu (0x%lX)\n", exp, exp);
	  mpz_trace ("  got ", got);
	  mpz_trace ("  want", want);
	  abort ();
	}
    }

  mpz_clear (got);
}
Beispiel #15
0
void field_init_tiny_fp(field_ptr f, mpz_t prime) {
  pbc_mpui *p;

  PBC_ASSERT(mpz_fits_ulong_p(prime), "modulus too big");

  field_init(f);
  f->init = fp_init;
  f->clear = fp_clear;
  f->set_si = fp_set_si;
  f->set_mpz = fp_set_mpz;
  f->out_str = fp_out_str;
  f->add = fp_add;
  f->sub = fp_sub;
  f->set = fp_set;
  f->mul = fp_mul;
  f->mul_si = fp_mul_si;
  f->square = fp_square;
  f->doub = fp_double;
  f->pow_mpz = fp_pow_mpz;
  f->neg = fp_neg;
  f->cmp = fp_cmp;
  f->sign = fp_sgn_odd;
  f->invert = fp_invert;
  f->random = fp_random;
  f->from_hash = fp_from_hash;
  f->is1 = fp_is1;
  f->is0 = fp_is0;
  f->set0 = fp_set0;
  f->set1 = fp_set1;
  f->is_sqr = fp_is_sqr;
  f->sqrt = element_tonelli;
  f->field_clear = fp_field_clear;
  f->to_bytes = fp_to_bytes;
  f->from_bytes = fp_from_bytes;
  f->to_mpz = fp_to_mpz;

  p = f->data = pbc_malloc(sizeof(pbc_mpui));
  *p = mpz_get_ui(prime);
  {
    pbc_mpui l = 255;
    f->fixed_length_in_bytes = 1;
    while (l < *p) {
      f->fixed_length_in_bytes++;
      l <<= 8;
      l += 255;
    }
  }
  mpz_set(f->order, prime);
}
Beispiel #16
0
cl_index
fixnnint(cl_object x)
{
        if (ECL_FIXNUMP(x)) {
                cl_fixnum i = ecl_fixnum(x);
                if (i >= 0)
                        return i;
        } else if (ECL_BIGNUMP(x)) {
                if (mpz_fits_ulong_p(x->big.big_num)) {
                        return mpz_get_ui(x->big.big_num);
                }
        }
	FEwrong_type_argument(cl_list(3, ECL_SYM("INTEGER",437), ecl_make_fixnum(0),
				      ecl_make_fixnum(MOST_POSITIVE_FIXNUM)),
			      x);
}
Beispiel #17
0
unsigned long vanilla::int_object_to_unsigned_long(object::ptr const& obj)
{
    if(obj->type_id() != OBJECT_ID_INT)
    {
        BOOST_THROW_EXCEPTION(error::bad_cast_error()
            << error::first_operand(obj)
            << error::cast_target_name("int"));
    }
    
    mpz_t& mpz = static_cast<int_object const*>(obj.get())->value().mpz();
    if(!mpz_fits_ulong_p(mpz) || mpz_sgn(mpz) == -1)
    {
        BOOST_THROW_EXCEPTION(error::integer_conversion_overflow_error()
            << error::first_operand(obj)
            << error::integer_conversion_target_type("unsigned long"));
    }
    return mpz_get_ui(mpz);
}
Beispiel #18
0
void field_init_fast_fp(field_ptr f, mpz_t prime) {
  PBC_ASSERT(!mpz_fits_ulong_p(prime), "modulus too small");
  fp_field_data_ptr p;
  field_init(f);
  f->init = fp_init;
  f->clear = fp_clear;
  f->set_si = fp_set_si;
  f->set_mpz = fp_set_mpz;
  f->out_str = fp_out_str;
  f->add = fp_add;
  f->sub = fp_sub;
  f->set = fp_set;
  f->mul = fp_mul;
  f->mul_si = fp_mul_si;
  f->square = fp_square;
  f->doub = fp_double;
  f->halve = fp_halve;
  f->pow_mpz = fp_pow_mpz;
  f->neg = fp_neg;
  f->cmp = fp_cmp;
  f->sign = mpz_odd_p(prime) ? fp_sgn_odd : fp_sgn_even;
  f->invert = fp_invert;
  f->random = fp_random;
  f->from_hash = fp_from_hash;
  f->is1 = fp_is1;
  f->is0 = fp_is0;
  f->set0 = fp_set0;
  f->set1 = fp_set1;
  f->is_sqr = fp_is_sqr;
  f->sqrt = element_tonelli;
  f->field_clear = fp_field_clear;
  f->to_bytes = fp_to_bytes;
  f->from_bytes = fp_from_bytes;
  f->to_mpz = fp_to_mpz;

  p = f->data = pbc_malloc(sizeof(fp_field_data_t));
  p->limbs = mpz_size(prime);
  p->bytes = p->limbs * sizeof(mp_limb_t);
  p->primelimbs = pbc_malloc(p->bytes);
  mpz_export(p->primelimbs, &p->limbs, -1, sizeof(mp_limb_t), 0, 0, prime);

  mpz_set(f->order, prime);
  f->fixed_length_in_bytes = (mpz_sizeinbase(prime, 2) + 7) / 8;
}
Beispiel #19
0
unsigned long int
mpz_gcd_ui (mpz_ptr w, mpz_srcptr u, unsigned long int v)
{
  mp_size_t un;
  mp_limb_t res;

#if BITS_PER_ULONG > GMP_NUMB_BITS  /* avoid warnings about shift amount */
  if (v > GMP_NUMB_MAX)
    {
      mpz_t vz;
      mp_limb_t vlimbs[2];
      vlimbs[0] = v & GMP_NUMB_MASK;
      vlimbs[1] = v >> GMP_NUMB_BITS;
      PTR(vz) = vlimbs;
      SIZ(vz) = 2;
      mpz_gcd (w, u, vz);
      /* because v!=0 we will have w<=v hence fitting a ulong */
      ASSERT (mpz_fits_ulong_p (w));
      return mpz_get_ui (w);
    }
Beispiel #20
0
void
check_all_inplace (mpz_ptr w, mpz_ptr y)
{
  int  wneg, yneg;

  MPZ_CHECK_FORMAT (w);
  MPZ_CHECK_FORMAT (y);

  for (wneg = 0; wneg < 2; wneg++)
    {
      for (yneg = 0; yneg < 2; yneg++)
        {
          check_one_inplace (w, y);

          if (mpz_fits_ulong_p (y))
            check_one_ui_inplace (w, mpz_get_ui (y));

          mpz_neg (y, y);
        }
      mpz_neg (w, w);
    }
}
Beispiel #21
0
/* read number to factor from 'params' file */
void
read_params (mpz_t N, unsigned long *B, unsigned long *LP, char *params)
{
  FILE *fp;
  mpz_t lp, bb;

  fp = fopen (params, "r");
  if (mpz_inp_str (N, fp, 10) == 0)
    {
      fprintf (stderr, "Error, cannot read number to factor\n");
      exit (1);
    }
  if (fscanf (fp, "%lu", B) == EOF)
    {
      fprintf (stderr, "Error, cannot read factor base bound\n");
      exit (1);
    }
  mpz_init (lp);
  mpz_init (bb);
  if (mpz_inp_str (lp, fp, 10) == 0)
    {
      mpz_set_ui (lp, *B);
      mpz_mul_ui (lp, lp, 128); 
    }
  /* LP must fit in a "unsigned long" (so that large primes can be
     represented by this type), and be less than B^2 (so that when
     a residue is less than LP, it is necessarily prime */
  mpz_ui_pow_ui (bb, *B, 2);
  if (mpz_fits_ulong_p (lp) == 0 || mpz_cmp (lp, bb) > 0)
    {
      fprintf (stderr, "Error, large prime bound is too large\n");
      exit (1);
    }
  *LP = mpz_get_ui (lp);
  mpz_clear (lp);
  mpz_clear (bb);
  fclose (fp);
}
void
one_test (mpz_t op1, mpz_t op2, mpz_t ref, int i)
{
  /*
  printf ("%ld %ld %ld\n", SIZ (op1), SIZ (op2), SIZ (ref));
  fflush (stdout);
  */

  /*
  fprintf (stderr, "op1=");  debug_mp (op1, -16);
  fprintf (stderr, "op2=");  debug_mp (op2, -16);
  */

  mpz_gcdext (gcd1, s, NULL, op1, op2);

  if (ref && mpz_cmp (ref, gcd1) != 0)
    {
      fprintf (stderr, "ERROR in test %d\n", i);
      fprintf (stderr, "mpz_gcdext returned incorrect result\n");
      fprintf (stderr, "op1=");                 debug_mp (op1, -16);
      fprintf (stderr, "op2=");                 debug_mp (op2, -16);
      fprintf (stderr, "expected result:\n");   debug_mp (ref, -16);
      fprintf (stderr, "mpz_gcdext returns:\n");debug_mp (gcd1, -16);
      abort ();
    }

  if (!gcdext_valid_p(op1, op2, gcd1, s))
    {
      fprintf (stderr, "ERROR in test %d\n", i);
      fprintf (stderr, "mpz_gcdext returned invalid result\n");
      fprintf (stderr, "op1=");                 debug_mp (op1, -16);
      fprintf (stderr, "op2=");                 debug_mp (op2, -16);
      fprintf (stderr, "mpz_gcdext returns:\n");debug_mp (gcd1, -16);
      abort ();
    }

  mpz_gcd (gcd2, op1, op2);
  if (mpz_cmp (gcd2, gcd1) != 0)
    {
      fprintf (stderr, "ERROR in test %d\n", i);
      fprintf (stderr, "mpz_gcd returned incorrect result\n");
      fprintf (stderr, "op1=");                 debug_mp (op1, -16);
      fprintf (stderr, "op2=");                 debug_mp (op2, -16);
      fprintf (stderr, "expected result:\n");   debug_mp (gcd1, -16);
      fprintf (stderr, "mpz_gcd returns:\n");   debug_mp (gcd2, -16);
      abort ();
    }

  /* This should probably move to t-gcd_ui.c */
  if (mpz_fits_ulong_p (op1) || mpz_fits_ulong_p (op2))
    {
      if (mpz_fits_ulong_p (op1))
	mpz_gcd_ui (gcd2, op2, mpz_get_ui (op1));
      else
	mpz_gcd_ui (gcd2, op1, mpz_get_ui (op2));
      if (mpz_cmp (gcd2, gcd1))
	{
	  fprintf (stderr, "ERROR in test %d\n", i);
	  fprintf (stderr, "mpz_gcd_ui returned incorrect result\n");
	  fprintf (stderr, "op1=");                 debug_mp (op1, -16);
	  fprintf (stderr, "op2=");                 debug_mp (op2, -16);
	  fprintf (stderr, "expected result:\n");   debug_mp (gcd1, -16);
	  fprintf (stderr, "mpz_gcd_ui returns:\n");   debug_mp (gcd2, -16);
	  abort ();
	}
    }

  mpz_gcdext (gcd2, temp1, temp2, op1, op2);
  mpz_mul (temp1, temp1, op1);
  mpz_mul (temp2, temp2, op2);
  mpz_add (temp1, temp1, temp2);
  
  if (mpz_cmp (gcd1, gcd2) != 0
      || mpz_cmp (gcd2, temp1) != 0)
    {
      fprintf (stderr, "ERROR in test %d\n", i);
      fprintf (stderr, "mpz_gcdext returned incorrect result\n");
      fprintf (stderr, "op1=");                 debug_mp (op1, -16);
      fprintf (stderr, "op2=");                 debug_mp (op2, -16);
      fprintf (stderr, "expected result:\n");   debug_mp (gcd1, -16);
      fprintf (stderr, "mpz_gcdext returns:\n");debug_mp (gcd2, -16);
      abort ();
    }
}
Beispiel #23
0
void field_init_mont_fp(field_ptr f, mpz_t prime) {
	PBC_ASSERT(!mpz_fits_ulong_p(prime), "modulus too small");
	fptr p;
	field_init(f);
	f->init = fp_init;
	f->clear = fp_clear;
	f->set_si = fp_set_si;
	f->set_mpz = fp_set_mpz;
	f->out_str = fp_out_str;
	f->snprint = fp_snprint;
	f->set_str = fp_set_str;
	f->add = fp_add;
	f->sub = fp_sub;
	f->set = fp_set;
	f->mul = fp_mul;
	f->doub = fp_double;
	f->halve = fp_halve;
	f->pow_mpz = fp_pow_mpz;
	f->neg = fp_neg;
	f->sign = fp_sgn_odd;
	f->cmp = fp_cmp;
	f->invert = fp_invert;
	f->random = fp_random;
	f->from_hash = fp_from_hash;
	f->is1 = fp_is1;
	f->is0 = fp_is0;
	f->set0 = fp_set0;
	f->set1 = fp_set1;
	f->is_sqr = fp_is_sqr;
	f->sqrt = element_tonelli;
	f->field_clear = fp_field_clear;
	f->to_bytes = fp_to_bytes;
	f->from_bytes = fp_from_bytes;
	f->to_mpz = fp_to_mpz;
	f->out_info = fp_out_info;

	// Initialize per-field data specific to this implementation.
	f->data = pbc_malloc(sizeof(*p));
	p = (fptr)f->data;
	p->limbs = mpz_size(prime);
	p->bytes = p->limbs * sizeof(mp_limb_t);
	p->primelimbs = (mp_limb_t*)pbc_malloc(p->bytes);
	mpz_export(p->primelimbs, &p->limbs, -1, sizeof(mp_limb_t), 0, 0, prime);
	mpz_set(f->order, prime);
	f->fixed_length_in_bytes = (mpz_sizeinbase(prime, 2) + 7) / 8;

	// Compute R, R3 and negpinv.
	mpz_t z;
	mpz_init(z);

	p->R = (mp_limb_t*)pbc_malloc(p->bytes);
	p->R3 = (mp_limb_t*)pbc_malloc(p->bytes);
	mpz_setbit(z, p->bytes * 8);
	mpz_mod(z, z, prime);
	set_limbs(p->R, z, p->limbs);

	mpz_powm_ui(z, z, 3, prime);
	set_limbs(p->R3, z, p->limbs);

	mpz_set_ui(z, 0);

	// Algorithm II.5 in Blake, Seroussi and Smart is better but this suffices
	// since we're only doing it once.
	mpz_setbit(z, p->bytes * 8);
	mpz_invert(z, prime, z);

#ifdef _MSC_VER		// for VC++ compatibility
	int tmp = mpz_get_ui(z);
	p->negpinv = -tmp;
#else
	p->negpinv = -mpz_get_ui(z);
#endif

	mpz_clear(z);
}
Beispiel #24
0
/* This is the custom formatter.
 * Note that this deals with grouping unlike the gmp_*printf() calls */
static int ex__usr_mpz_cb(Vstr_base *base, size_t pos, Vstr_fmt_spec *spec,
                          char fmt, const mpz_t val)
{
  unsigned int nb = 10;
  int flags = VSTR_FLAG_SC_FMT_CB_BEG_OBJ_NUM; /* it's a number */
  size_t len = 0;
  int ret = FALSE;
  char ui_buf[(sizeof(unsigned long) * CHAR_BIT) + 1];
  char *buf = NULL;
  char *out_buf = ui_buf;
  
  switch (fmt)
  {
    case 'd':                                                         break;
    case 'x': nb = 16; flags |= VSTR_FLAG_SC_FMT_CB_BEG_OBJ_HEXNUM_L; break;
    case 'o': nb =  8; flags |= VSTR_FLAG_SC_FMT_CB_BEG_OBJ_OCTNUM;   break;
    case 'b': nb =  2; flags |= VSTR_FLAG_SC_FMT_CB_BEG_OBJ_BINNUM_L; break;
    default: ASSERT(FALSE);                                           break;
  }
  
  if (mpz_sgn(val) == -1)
    flags |= VSTR_FLAG_SC_FMT_CB_BEG_OBJ_NEG;
  
  if (mpz_fits_ulong_p(val))
    len = vstr_sc_conv_num_ulong(ui_buf, sizeof(ui_buf), mpz_get_ui(val),
                                 "0123456789abcdef", nb);
  else
  {
    len = mpz_sizeinbase(val, nb);
    out_buf = buf = mpz_get_str(NULL, nb, val); /* dies on malloc error */

    if (mpz_sgn(val) == -1) ++out_buf;
    if (!out_buf[len - 1])  --len; /* see documentation for mpz_sizeinbase() */
  }

  ASSERT(strlen(out_buf) == len);
  
  if (!vstr_sc_fmt_cb_beg(base, &pos, spec, &len, flags))
    goto mem_fail;
 
  if (spec->fmt_quote) /* add number including grouping */
    ret = vstr_sc_add_grpbasenum_buf(base, pos, nb, out_buf, len);
  else if (!EX_GMP_NUMS_USE_REFS || !buf) /* just add the number */
    ret = vstr_add_buf(base, pos, out_buf, len);
  else
  { /* assumes mp_set_memory_functions() hasn't been called */
    Vstr_ref *ref = vstr_ref_make_ptr(buf, vstr_ref_cb_free_ptr_ref);

    if (!ref)
      goto mem_fail;

    ret = vstr_add_ref(base, pos, ref, out_buf - buf, len);
    
    buf = NULL; /* memory is free'd when the reference is used up */

    /* if !ret then this will free buf */
    vstr_ref_del(ref);
  }
  
  if (!ret || !vstr_sc_fmt_cb_end(base, pos, spec, len))
    goto mem_fail;

  free(buf);
  
  return (TRUE);

 mem_fail:
  free(buf);
  return (FALSE);
}
Beispiel #25
0
int
main (int argc, char **argv)
{
    mpz_t op1, op2, r1, r2;
    mp_size_t op1n, op2n;
    unsigned long int op2long;
    int i;
    int reps = 100000;
    gmp_randstate_ptr rands;
    mpz_t bs;
    unsigned long bsi, size_range;

    tests_start ();
    rands = RANDS;

    mpz_init (bs);

    if (argc == 2)
        reps = atoi (argv[1]);

    mpz_init (op1);
    mpz_init (op2);
    mpz_init (r1);
    mpz_init (r2);

    for (i = 0; i < reps; i++)
    {
        mpz_urandomb (bs, rands, 32);
        size_range = mpz_get_ui (bs) % 10 + 2;

        mpz_urandomb (bs, rands, size_range);
        op1n = mpz_get_ui (bs);
        mpz_rrandomb (op1, rands, op1n);

        mpz_urandomb (bs, rands, size_range);
        op2n = mpz_get_ui (bs);
        mpz_rrandomb (op2, rands, op2n);

        mpz_urandomb (bs, rands, 2);
        bsi = mpz_get_ui (bs);
        if ((bsi & 1) != 0)
            mpz_neg (op1, op1);
        if ((bsi & 2) != 0)
            mpz_neg (op2, op2);

        /* printf ("%ld %ld\n", SIZ (multiplier), SIZ (multiplicand)); */

        mpz_add (r1, op1, op2);
        mpz_sub (r2, r1, op2);
        if (mpz_cmp (r2, op1) != 0)
            dump_abort (i, "mpz_add or mpz_sub incorrect", op1, op2);

        if (mpz_fits_ulong_p (op2))
        {
            op2long = mpz_get_ui (op2);
            mpz_add_ui (r1, op1, op2long);
            mpz_sub_ui (r2, r1, op2long);
            if (mpz_cmp (r2, op1) != 0)
                dump_abort (i, "mpz_add_ui or mpz_sub_ui incorrect", op1, op2);

            mpz_ui_sub (r1, op2long, op1);
            mpz_sub_ui (r2, op1, op2long);
            mpz_neg (r2, r2);
            if (mpz_cmp (r1, r2) != 0)
                dump_abort (i, "mpz_add_ui or mpz_ui_sub incorrect", op1, op2);
        }
    }

    mpz_clear (bs);
    mpz_clear (op1);
    mpz_clear (op2);
    mpz_clear (r1);
    mpz_clear (r2);

    tests_end ();
    exit (0);
}
Beispiel #26
0
bool RingZZ::get_ui(unsigned int &result, mpz_t n)
{
  result = static_cast<unsigned int>(mpz_get_ui(n));
  return mpz_fits_ulong_p(n);
}
Beispiel #27
0
static int
e_mpq_ulong_p (mpq_srcptr q)
{
  return mpz_fits_ulong_p (mpq_numref (q))
    && mpz_cmp_ui (mpq_denref (q), 1L) == 0;
}
Beispiel #28
0
static PyObject *
GMPy_Integer_Pow(PyObject *b, PyObject *e, PyObject *m, CTXT_Object *context)
{
    MPZ_Object *result = NULL, *tempb = NULL, *tempe = NULL, *tempm = NULL;
    int has_mod;

    /* Try to parse the modulus value first. */

    if (m == Py_None) {
        has_mod = 0;
    }
    else {
        has_mod = 1;
        if (!IS_INTEGER(m)) {
            Py_RETURN_NOTIMPLEMENTED;
        }
        else {
            if (!(tempm = GMPy_MPZ_From_Integer(m, context))) {
                goto err;
            }
        }
    }

    result = GMPy_MPZ_New(context);
    tempb = GMPy_MPZ_From_Integer(b, context);
    tempe = GMPy_MPZ_From_Integer(e, context);

    if (!tempb || !tempe || !result) {
        goto err;
    }

    if (!has_mod) {
        /* When no modulo is present, the exponent must fit in unsigned long.
         */
        unsigned long el;

        if (mpz_sgn(tempe->z) < 0) {
            VALUE_ERROR("pow() exponent cannot be negative");
            goto err;
        }

        if (!mpz_fits_ulong_p(tempe->z)) {
            VALUE_ERROR("pow() outrageous exponent");
            goto err;
        }

        el = mpz_get_ui(tempe->z);
        mpz_pow_ui(result->z, tempb->z, el);
    }
    else {
        /* Modulo is present. */
        int sign;
        mpz_t mm, base, exp;

        sign = mpz_sgn(tempm->z);
        if (sign == 0) {
            VALUE_ERROR("pow() 3rd argument cannot be 0");
            goto err;
        }

        mpz_inoc(mm);
        mpz_abs(mm, tempm->z);

        /* A negative exponent is allowed if inverse exists. */
        if (mpz_sgn(tempe->z) < 0) {
            mpz_inoc(base);
            mpz_inoc(exp);

            if (!mpz_invert(base, tempb->z, mm)) {
                VALUE_ERROR("pow() base not invertible");
                mpz_cloc(base);
                mpz_cloc(exp);
                mpz_cloc(mm);
                goto err;
            }
            else {
                mpz_abs(exp, tempe->z);
            }

            mpz_powm(result->z, base, exp, mm);
            mpz_cloc(base);
            mpz_cloc(exp);
        }
        else {
            mpz_powm(result->z, tempb->z, tempe->z, mm);
        }
        mpz_cloc(mm);

        /* Python uses a rather peculiar convention for negative modulos
         * If the modulo is negative, result should be in the interval
         * m < r <= 0 .
         */
        if ((sign < 0) && (mpz_sgn(MPZ(result)) > 0)) {
            mpz_add(result->z, result->z, tempm->z);
        }
    }
    Py_XDECREF((PyObject*)tempb);
    Py_XDECREF((PyObject*)tempe);
    Py_XDECREF((PyObject*)tempm);
    return (PyObject*)result;

  err:
    Py_XDECREF((PyObject*)tempb);
    Py_XDECREF((PyObject*)tempe);
    Py_XDECREF((PyObject*)tempm);
    Py_DECREF((PyObject*)result);
    return NULL;
}
Beispiel #29
0
void
check_all (mpz_ptr want, mpz_srcptr x_orig, mpz_srcptr y_orig)
{
  mpz_t  got, x, y;
  int    negx, negy, swap, inplace;

  mpz_init (got);
  mpz_init_set (x, x_orig);
  mpz_init_set (y, y_orig);

  for (swap = 0; swap < 2; swap++)
    {
      mpz_swap (x, y);

      for (negx = 0; negx < 2; negx++)
	{
	  mpz_neg (x, x);

	  for (negy = 0; negy < 2; negy++)
	    {
	      mpz_neg (y, y);

	      for (inplace = 0; inplace <= 1; inplace++)
		{
		  if (inplace)
		    { mpz_set (got, x); mpz_lcm (got, got, y); }
		  else
		    mpz_lcm (got, x, y);
		  MPZ_CHECK_FORMAT (got);

		  if (mpz_cmp (got, want) != 0)
		    {
		      printf ("mpz_lcm wrong, inplace=%d\n", inplace);
		    fail:
		      mpz_trace ("x", x);
		      mpz_trace ("y", y);
		      mpz_trace ("got", got);
		      mpz_trace ("want", want);
		      abort ();
		    }

		  if (mpz_fits_ulong_p (y))
		    {
		      unsigned long  yu = mpz_get_ui (y);
		      if (inplace)
			{ mpz_set (got, x); mpz_lcm_ui (got, got, yu); }
		      else
			mpz_lcm_ui (got, x, yu);

		      if (mpz_cmp (got, want) != 0)
			{
			  printf ("mpz_lcm_ui wrong, inplace=%d\n", inplace);
			  printf    ("yu=%lu\n", yu);
			  goto fail;
			}
		    }
		}
	    }
	}
    }

  mpz_clear (got);
  mpz_clear (x);
  mpz_clear (y);
}
Beispiel #30
0
num_t
num_int_part_sel(pseltype_t op_type, num_t hi, num_t lo, num_t a)
{
	num_t r, m;
	unsigned long mask_shl, lo_ui;

	r = num_new_z(N_TEMP, NULL);
	m = num_new_z(N_TEMP, NULL);
	a = num_new_z(N_TEMP, a);
	hi = num_new_z(N_TEMP, hi);
	if (lo != NULL)
		lo = num_new_z(N_TEMP, lo);

	switch (op_type) {
	case PSEL_SINGLE:
		lo = num_new_z(N_TEMP, hi);
		break;

	case PSEL_FRANGE:
		break;

	case PSEL_DRANGE:
		if (mpz_cmp_si(Z(lo), 0L) < 0) {
			yyxerror("low index of part select operation must be "
			    "positive");
			return NULL;
		}
		mpz_sub_ui(Z(lo), Z(lo), 1UL);
		mpz_sub(Z(lo), Z(hi), Z(lo));
		break;
	}

	if (mpz_cmp_si(Z(hi), 0L) < 0) {
		yyxerror("high index of part select operation must be "
		    "positive");
		return NULL;
	}

	if (mpz_cmp_si(Z(lo), 0L) < 0) {
		yyxerror("low index of part select operation must be "
		    "positive");
		return NULL;
	}

	if (!mpz_fits_ulong_p(Z(hi))) {
		yyxerror("high index of part select operation needs to fit "
		    "into an unsigned long C datatype");
		return NULL;
	}

	if (!mpz_fits_ulong_p(Z(lo))) {
		yyxerror("low index of part select operation needs to fit "
		    "into an unsigned long C datatype");
		return NULL;
	}

	lo_ui = mpz_get_ui(Z(lo));
	mask_shl = 1 + (mpz_get_ui(Z(hi)) - lo_ui);

	/*
	 * We do the part sel by:
	 *  (1) shifting right by 'lo'
	 *  (2) anding with ((1 << mask_shl)-1)
	 */
	mpz_div_2exp(Z(r), Z(a), lo_ui);
	mpz_set_ui(Z(m), 1UL);
	mpz_mul_2exp(Z(m), Z(m), mask_shl);
	mpz_sub_ui(Z(m), Z(m), 1UL);

	mpz_and(Z(r), Z(r), Z(m));

	return r;
}