예제 #1
0
파일: bit.c 프로젝트: mahdiz/mpclib
void
check_single (void)
{
  mpz_t  x;
  int    limb, offset, initial;
  unsigned long  bit;

  mpz_init (x);

  for (limb = 0; limb < 4; limb++)
    {
      for (offset = (limb==0 ? 0 : -2); offset <= 2; offset++)
        {
          for (initial = 0; initial >= -1; initial--)
            {
              mpz_set_si (x, (long) initial);

              bit = (unsigned long) limb*BITS_PER_MP_LIMB + offset;

              mpz_clrbit (x, bit);
              MPZ_CHECK_FORMAT (x);
              if (mpz_tstbit (x, bit) != 0)
                {
                  printf ("check_single(): expected 0\n");
                  abort ();
                }
          
              mpz_setbit (x, bit);
              MPZ_CHECK_FORMAT (x);
              if (mpz_tstbit (x, bit) != 1)
                {
                  printf ("check_single(): expected 0\n");
                  abort ();
                }
          
              mpz_clrbit (x, bit);
              MPZ_CHECK_FORMAT (x);
              if (mpz_tstbit (x, bit) != 0)
                {
                  printf ("check_single(): expected 0\n");
                  abort ();
                }
            }
        }
    }          

  mpz_clear (x);
}
예제 #2
0
파일: exprz.c 프로젝트: mahdiz/mpclib
static void
e_mpz_clrbit (mpz_ptr w, mpz_srcptr x, unsigned long n)
{
  if (w != x)
    mpz_set (w, x);
  mpz_clrbit (w, n);
}
예제 #3
0
static PyObject *
GMPy_MPZ_bit_clear_function(PyObject *self, PyObject *args)
{
    mp_bitcnt_t bit_index;
    MPZ_Object *result = NULL, *tempx = NULL;

    if (PyTuple_GET_SIZE(args) != 2)
        goto err;

    if (!(result = GMPy_MPZ_New(NULL)))
        return NULL;

    if (!(tempx = GMPy_MPZ_From_Integer(PyTuple_GET_ITEM(args, 0), NULL)))
        goto err;

    bit_index = mp_bitcnt_t_From_Integer(PyTuple_GET_ITEM(args, 1));
    if (bit_index == (mp_bitcnt_t)(-1) && PyErr_Occurred())
        goto err_index;

    mpz_set(result->z, tempx->z);
    mpz_clrbit(result->z, bit_index);

    Py_DECREF((PyObject*)tempx);
    return (PyObject*)result;

  err:
    TYPE_ERROR("bit_clear() requires 'mpz','int' arguments");
  err_index:
    Py_XDECREF((PyObject*)result);
    Py_XDECREF((PyObject*)tempx);
    return NULL;
}
예제 #4
0
void
mpz_flipbit (mpz_ptr r, unsigned long bit)
{
  if (mpz_tstbit (r, bit))
    mpz_clrbit (r, bit);
  else
    mpz_setbit (r, bit);
}
예제 #5
0
파일: testutils.c 프로젝트: AllardJ/Tomato
/* Missing in current gmp */
static void
mpz_togglebit (mpz_t x, unsigned long int bit)
{
  if (mpz_tstbit(x, bit))
    mpz_clrbit(x, bit);
  else
    mpz_setbit(x, bit);
}
예제 #6
0
	void LNSMul::emulate(TestCase * tc)
	{
		mpz_class a = tc->getInputValue("nA");
		mpz_class b = tc->getInputValue("nB");
		
		bool sr = mpz_tstbit(a.get_mpz_t(), wE+wF) ^ mpz_tstbit(b.get_mpz_t(), wE+wF);
		bool xa0 = mpz_tstbit(a.get_mpz_t(), wE+wF+1);
		bool xa1 = mpz_tstbit(a.get_mpz_t(), wE+wF+2);
		bool xb0 = mpz_tstbit(b.get_mpz_t(), wE+wF+1);
		bool xb1 = mpz_tstbit(b.get_mpz_t(), wE+wF+2);
		bool xr0,xr1;
		
		bool nan = (xa0 & xa1) | (xb0 & xb1);		// 11
		bool zero = !(xa0 | xa1) | !(xb0 | xb1);	// 00
		bool inf = (xa1 & !xa0) | (xb1 & !xb0);		// 10
		
		mpz_class r = a + b;
		bool ovf = (mpz_sizeinbase(r.get_mpz_t(), 2) > unsigned(wE+wF)) && (sgn(r) > 0);
		bool udf = (mpz_sizeinbase(r.get_mpz_t(), 2) > unsigned(wE+wF)) && (sgn(r) < 0);

		if(nan | (zero & inf)) {
			xr0 = xr1 = 1;
		}
		else if(zero) {
			xr1 = xr0 = 0;
		}
		else if(inf | ovf) {
			xr1 = 1;
			xr0 = 0;
		}
		else if(udf) {
			xr1 = xr0 = 0;
		}
		else {
			xr1 = 0;
			xr0 = 1;
		}
		if(sr) mpz_setbit(r.get_mpz_t(), wE+wF); else mpz_clrbit(r.get_mpz_t(), wE+wF);
		if(xr0) mpz_setbit(r.get_mpz_t(), wE+wF+1); else mpz_clrbit(r.get_mpz_t(), wE+wF+1);
		if(xr1) mpz_setbit(r.get_mpz_t(), wE+wF+2); else mpz_clrbit(r.get_mpz_t(), wE+wF+2);
		r &= mpzpow2(wE+wF+3)-1;	// Discard overflowing bits
		
		tc->addExpectedOutput("nR", r);
	}
예제 #7
0
static void mympz_from_hash(mpz_t x, mpz_t limit, byte_string_t hash)
//let z = number represented in c
//x = z || 1 || z || 2 || z || 3 ...
//until there are enough bits
//should be rewritten more efficiently?
{
    mpz_t z;
    int countlen;
    mpz_t count;
    int i = 0, j;
    int bits = mpz_sizeinbase(limit, 2);
    int zbits;
    char *c = hash->data;
    int len = hash->len;

    mpz_init(z);
    mpz_init(count);
    mpz_set_ui(count, 1);

    mympz_inp_raw(z, c, len);
    zbits = mpz_sizeinbase(z, 2);

    mpz_set_ui(x, 0);
    do {
	for (j=0; j<zbits; j++) {
	    if (mpz_tstbit(z, j)) {
		mpz_setbit(x, i);
	    }
	    i++;
	}
	bits -= zbits;
	if (bits <= 0) break;

	countlen = mpz_sizeinbase(count, 2);
	for (j=0; j<countlen; j++) {
	    if (mpz_tstbit(count, j)) {
		mpz_setbit(x, i);
	    }
	    i++;
	}
	bits -= countlen;
	mpz_add_ui(count, count, 1);
    } while (bits > 0);
    /*
    printf("hash: ");
    mpz_out_str(NULL, 0, x);
    printf("\n");
    */
    while (mpz_cmp(x, limit) > 0) {
	mpz_clrbit(x, mpz_sizeinbase(x, 2) - 1);
    }

    mpz_clear(z);
    mpz_clear(count);
}
예제 #8
0
	void LongIntAdderMuxNetwork::emulate(TestCase* tc)
	{
		mpz_class svX[2];
		for (int i=0; i<2; i++){
			ostringstream iName;
			iName << "X"<<i;
			svX[i] = tc->getInputValue(iName.str());
		}
		mpz_class svC =  tc->getInputValue("Cin");

		mpz_class svR = svX[0] + svC;
		mpz_clrbit(svR.get_mpz_t(),wIn_); 
		for (int i=1; i<2; i++){
			svR = svR + svX[i];
			mpz_clrbit(svR.get_mpz_t(),wIn_); 
		}

		tc->addExpectedOutput("R", svR);

	}
예제 #9
0
파일: bignum.c 프로젝트: libbitc/libbitc
void bn_setvch(mpz_t vo, const void *data_, size_t data_len)
{
	const unsigned char *data = data_;

	mpz_import(vo, data_len, -1, 1, 1, 0, data);

	if ((data_len > 0) && (data[data_len - 1] & 0x80)) {
		mpz_clrbit(vo, mpz_sizeinbase(vo, 2) - 1);
		mpz_neg(vo, vo);
	}
}
void Element::multiply(Element& A, Element& B) {
	// Emulate hardware implementation.
	
	// Set result to 0
	mpz_t result;
	mpz_init(result);
	
	// Modulus: x^163 + x^7 + x^6 + x^3 + 1 (wordlength 163)
	mpz_t mod;
	mpz_init(mod);
	mpz_set_str(mod, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011001001", 2);
	
	//gmp_printf("Mod = %Zx\n", mod);
	
	// Length of modulus in base 2
	int mod_len = 163;
	
	//printf("Len = %d\n", mod_len);
	
	int m = 0;
	for (long i = (long) mod_len; i > 0; i--) {
		if (mpz_tstbit(A.getMP(), i - 1) == 1) {
			mpz_xor(result, result, B.getMP());
		}
		
		if (m == 1) {
			mpz_xor(result, result, mod);
		}
		
		// Set m & T for next round
		m = mpz_tstbit(result, mod_len - 1);
		
		// Shift T by 1 bit to the left and clear MSB bit
		mpz_clrbit(result, mod_len - 1);
		mpz_mul_2exp(result, result, 1);
		
		/*printf("[Mult] i = %d - T = ", mod_len - i + 2);
		gmp_printf("0x%Zx\n", result);*/
	}
	
	// Shift result back 1 place & place m back in front
	mpz_tdiv_q_2exp(result, result, 1);
	if (m == 1) {
		mpz_setbit(result, 162);
	}
	
	/*printf("[Mult] i = 0 - T = ");
	gmp_printf("0x%Zx\n", result);*/
	
	// Set result
	mpz_set(this->a, result);
}
예제 #11
0
파일: rw.c 프로젝트: agl/rwb0fuz1024
// -----------------------------------------------------------------------------
// Generate a random prime number and store the result in @n.
//
// urfd: a file descriptor opened to a random source
// size: the (approx) size in bits for the resulting prime
// mod8: the prime, mod 8, shall be equal to this
// -----------------------------------------------------------------------------
static void
init_random_prime(mpz_t n, int urfd, unsigned size, unsigned mod8) {
  uint8_t buffer[2048];
  const unsigned bytes = size >> 3;

  if (bytes > sizeof(buffer))
    abort();

  mpz_init2(n, bytes);

  for (;;) {
    ssize_t r;

    do {
      r = read(urfd, buffer, bytes);
    } while (r == -1 && errno == EINTR);

    if (r != bytes)
      abort();

    mpz_import(n, bytes, 1, 1, 0, 0, buffer);
    mpz_setbit(n, 0);

    if (mod8 & 2) {
      mpz_setbit(n, 1);
    } else {
      mpz_clrbit(n, 1);
    }

    if (mod8 & 4) {
      mpz_setbit(n, 2);
    } else {
      mpz_clrbit(n, 2);
    }

    if (mpz_probab_prime_p(n, 10))
      break;
  }
}
예제 #12
0
파일: arith.c 프로젝트: gsmadhusudan/Balsa
/* RecoverSign : sign extend a MP_INT with the bit width-1 */
void RecoverSign (PtrMP_INT val, Bits width)
{
    mpz_setbit (val, width);

    if (mpz_scan1 (val, width - 1) == width - 1)
    {
        PtrMP_INT bitMask = MakeMaskForRange (width, 0);

        mpz_com (bitMask, bitMask); /* 00001111 -> 11110000 */
        mpz_ior (val, val, bitMask);
        DeleteMP_INT (bitMask);
    } else
        mpz_clrbit (val, width);
}
예제 #13
0
파일: bit.c 프로젝트: RodneyBates/M3Devel
/* exercise the case where mpz_clrbit or mpz_combit ends up extending a
   value like -2^(k*GMP_NUMB_BITS-1) when clearing bit k*GMP_NUMB_BITS-1.  */
void
check_clr_extend (void)
{
  mpz_t          got, want;
  unsigned long  i;
  int            f;

  mpz_init (got);
  mpz_init (want);

  for (i = 1; i < 5; i++)
    {
      for (f = 0; f <= 1; f++)
	{
	  /* lots of 1 bits in _mp_d */
	  mpz_set_ui (got, 1L);
	  mpz_mul_2exp (got, got, 10*GMP_NUMB_BITS);
	  mpz_sub_ui (got, got, 1L);

	  /* value -2^(n-1) representing ..11100..00 */
	  mpz_set_si (got, -1L);
	  mpz_mul_2exp (got, got, i*GMP_NUMB_BITS-1);

	  /* complement bit n, giving ..11000..00 which is -2^n */
	  if (f == 0)
	    mpz_clrbit (got, i*GMP_NUMB_BITS-1);
	  else
	    mpz_combit (got, i*GMP_NUMB_BITS-1);
	  MPZ_CHECK_FORMAT (got);

	  mpz_set_si (want, -1L);
	  mpz_mul_2exp (want, want, i*GMP_NUMB_BITS);

	  if (mpz_cmp (got, want) != 0)
	    {
	      if (f == 0)
		printf ("mpz_clrbit: ");
	      else
		printf ("mpz_combit: ");
	      printf ("wrong after extension\n");
	      mpz_trace ("got ", got);
	      mpz_trace ("want", want);
	      abort ();
	    }
	}
    }

  mpz_clear (got);
  mpz_clear (want);
}
예제 #14
0
static PyObject *
GMPy_MPZ_bit_clear_method(PyObject *self, PyObject *other)
{
    mp_bitcnt_t bit_index;
    MPZ_Object *result = NULL;

    if (!(result = GMPy_MPZ_New(NULL)))
        return NULL;

    bit_index = mp_bitcnt_t_From_Integer(other);
    if (bit_index == (mp_bitcnt_t)(-1) && PyErr_Occurred())
        return NULL;

    mpz_set(result->z, MPZ(self));
    mpz_clrbit(result->z, bit_index);
    return (PyObject*)result;
}
예제 #15
0
static void HHVM_FUNCTION(gmp_clrbit,
                          VRefParam& data,
                          int64_t index) {

  if (index < 0) {
    raise_warning(cs_GMP_INVALID_INDEX_IS_NEGATIVE,
                  cs_GMP_FUNC_NAME_GMP_CLRBIT);
    return;
  }

  auto gmpRes = data.toResource().getTyped<GMPResource>(true, true);
  if (!gmpRes) {
    raise_warning(cs_GMP_FAILED_TO_ALTER_BIT, cs_GMP_FUNC_NAME_GMP_CLRBIT);
    return;
  }

  mpz_clrbit(gmpRes->getData(), index);
}
예제 #16
0
파일: clrbit.c 프로젝트: clear731/lattice
void fmpz_clrbit(fmpz_t f, ulong i)
{
    if (!COEFF_IS_MPZ(*f))
    {
        if (i < FLINT_BITS - 2)
        {
            *f &= ~(WORD(1) << i);
        }
        /* i >= FLINT_BITS  --> nop */
    }
    else
    {
        __mpz_struct *ptr = COEFF_TO_PTR(*f);

        mpz_clrbit(ptr, i);
        _fmpz_demote_val(f);
    }
}
예제 #17
0
static void
randseed_mt (gmp_randstate_t rstate, mpz_srcptr seed)
{
  int i;
  size_t cnt;

  gmp_rand_mt_struct *p;
  mpz_t mod;    /* Modulus.  */
  mpz_t seed1;  /* Intermediate result.  */

  p = (gmp_rand_mt_struct *) RNG_STATE (rstate);

  mpz_init2 (mod, 19938L);
  mpz_init2 (seed1, 19937L);

  mpz_setbit (mod, 19937L);
  mpz_sub_ui (mod, mod, 20027L);
  mpz_mod (seed1, seed, mod);	/* Reduce `seed' modulo `mod'.  */
  mpz_clear (mod);
  mpz_add_ui (seed1, seed1, 2L);	/* seed1 is now ready.  */
  mangle_seed (seed1);	/* Perform the mangling by powering.  */

  /* Copy the last bit into bit 31 of mt[0] and clear it.  */
  p->mt[0] = (mpz_tstbit (seed1, 19936L) != 0) ? 0x80000000 : 0;
  mpz_clrbit (seed1, 19936L);

  /* Split seed1 into N-1 32-bit chunks.  */
  mpz_export (&p->mt[1], &cnt, -1, sizeof (p->mt[1]), 0,
              8 * sizeof (p->mt[1]) - 32, seed1);
  mpz_clear (seed1);
  cnt++;
  ASSERT (cnt <= N);
  while (cnt < N)
    p->mt[cnt++] = 0;

  /* Warm the generator up if necessary.  */
  if (WARM_UP != 0)
    for (i = 0; i < WARM_UP / N; i++)
      __gmp_mt_recalc_buffer (p->mt);

  p->mti = WARM_UP % N;
}
예제 #18
0
ssv_t *asc_ssv_gather(ssv_t *x, pid_t pid)
{
#if ASC_TRACE
    fprintf(stderr, "GATHER\n");
#endif
    int (*peek)(struct iovec *, struct iovec *, pid_t);
    struct iovec local, *remote;
    long i, bits;

    /* Allocate new memory only if necessary.  */
    if (x == 0)
        if ((x = asc_ssv_bind(0, pid)) == 0)
            goto failure;

    /* Walk through the dense subvectors of the sparse state vector `x'.  */
    for (i = 0; i < x->N; i++) {
        peek = x->sub[i].peek;

        if (peek) {
            remote = &x->sub[i].iov;
            bits = 8 * remote->iov_len;

            assert(bits > 0);

            /* Force memory allocation.  */
            mpz_setbit(x->sub[i].z, bits);

            local.iov_base = x->sub[i].z->_mp_d;
            local.iov_len = remote->iov_len;

            if (peek(&local, remote, pid))
                goto failure;

            mpz_clrbit(x->sub[i].z, bits);
        }
    }

    return x;

failure:
    return 0;
}
예제 #19
0
void sieving_for(uint64_t index, uint64_t prime_number, uint64_t prime_number_position, smooth_number_t** smooth_array, uint64_t size_base){

  uint64_t i, bit;
  smooth_number_t* smooth;

  for( i = index; i < size_base; i = i + prime_number ){
    smooth = smooth_array[i];
    mpz_cdiv_q_ui(smooth->result, smooth->result, prime_number);

    smooth->exponents[prime_number_position]++;

    if( mpz_tstbit(smooth->exponents_mod_2, prime_number_position) ){
      mpz_clrbit(smooth->exponents_mod_2, prime_number_position);
    }
    else{
      mpz_setbit(smooth->exponents_mod_2, prime_number_position);
    }

  }

}
예제 #20
0
void
check_onebit (void)
{
  mpz_t          n;
  unsigned long  i, got;

  mpz_init (n);
  for (i = 0; i < 5 * GMP_LIMB_BITS; i++)
    {
      mpz_setbit (n, i);
      got = mpz_popcount (n);
      if (got != 1)
	{
	  printf ("mpz_popcount wrong on single bit at %lu\n", i);
	  printf ("   got %lu, want 1\n", got);
	  abort();
	}
      mpz_clrbit (n, i);
    }
  mpz_clear (n);
}
예제 #21
0
파일: gen-bases.c 프로젝트: Cl3Kener/gmp
void
generate (int limb_bits, int nail_bits, int base)
{
  int  numb_bits = limb_bits - nail_bits;

  mpz_set_ui (t, 1L);
  mpz_mul_2exp (t, t, numb_bits);
  mpz_set_ui (big_base, (long) base);
  chars_per_limb = 0;
  while (mpz_cmp (big_base, t) <= 0)
    {
      mpz_mul_ui (big_base, big_base, (long) base);
      chars_per_limb++;
    }

  mpz_ui_pow_ui (big_base, (long) base, (long) chars_per_limb);

  normalization_steps = limb_bits - mpz_sizeinbase (big_base, 2);

  mpz_set_ui (t, 1L);
  mpz_mul_2exp (t, t, 2*limb_bits - normalization_steps);
  mpz_tdiv_q (big_base_inverted, t, big_base);
  mpz_clrbit (big_base_inverted, limb_bits);
}
static dckey *
rw_keygen (size_t nbits, const char *extra)
{
  rw_priv *sk = malloc (sizeof (*sk));
  int bit2;

  if (!sk)
    return NULL;

  mpz_init (sk->n);
  mpz_init (sk->p);
  mpz_init (sk->q);
  mpz_init (sk->u);
  mpz_init (sk->kp);
  mpz_init (sk->kq);

  do {
    random_bigint (sk->p, (nbits+1)/2);
    mpz_setbit (sk->p, 0);
    mpz_setbit (sk->p, 1);
  } while (!primecheck (sk->p));

  bit2 = ~mpz_get_ui (sk->p) & 4;
  do {
    random_bigint (sk->q, nbits/2);
    mpz_setbit (sk->q, 0);
    mpz_setbit (sk->q, 1);
    if (bit2)
      mpz_setbit (sk->q, 2);
    else
      mpz_clrbit (sk->q, 2);
  } while (!primecheck (sk->q));

  rw_precompute (sk);
  return &sk->key;
}
예제 #23
0
파일: hex-random.c 프로젝트: AllardJ/Tomato
void
hex_random_bit_op (enum hex_random_op op, unsigned long maxbits,
		   char **ap, unsigned long *b, char **rp)
{
  mpz_t a, r;
  unsigned long abits, bbits;
  unsigned signs;

  mpz_init (a);
  mpz_init (r);

  abits = gmp_urandomb_ui (state, 32) % maxbits;
  bbits = gmp_urandomb_ui (state, 32) % (maxbits + 100);

  mpz_rrandomb (a, state, abits);

  signs = gmp_urandomb_ui (state, 1);
  if (signs & 1)
    mpz_neg (a, a);

  switch (op)
    {
    default:
      abort ();

    case OP_SETBIT:
      mpz_set (r, a);
      mpz_setbit (r, bbits);
      break;
    case OP_CLRBIT:
      mpz_set (r, a);
      mpz_clrbit (r, bbits);
      break;
    case OP_COMBIT:
      mpz_set (r, a);
      mpz_combit (r, bbits);
      break;
    case OP_CDIV_Q_2:
      mpz_cdiv_q_2exp (r, a, bbits);
      break;
    case OP_CDIV_R_2:
      mpz_cdiv_r_2exp (r, a, bbits);
      break;
    case OP_FDIV_Q_2:
      mpz_fdiv_q_2exp (r, a, bbits);
      break;
    case OP_FDIV_R_2:
      mpz_fdiv_r_2exp (r, a, bbits);
      break;
    case OP_TDIV_Q_2:
      mpz_tdiv_q_2exp (r, a, bbits);
      break;
    case OP_TDIV_R_2:
      mpz_tdiv_r_2exp (r, a, bbits);
      break;
    }

  gmp_asprintf (ap, "%Zx", a);
  *b = bbits;
  gmp_asprintf (rp, "%Zx", r);

  mpz_clear (a);
  mpz_clear (r);
}
예제 #24
0
파일: bit.c 프로젝트: mahdiz/mpclib
void
check_random (int argc, char *argv[])
{
  mpz_t x, s0, s1, s2, s3, m;
  mp_size_t xsize;
  int i;
  int reps = 100000;
  int bit0, bit1, bit2, bit3;
  unsigned long int bitindex;
  const char  *s = "";

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

  mpz_init (x);
  mpz_init (s0);
  mpz_init (s1);
  mpz_init (s2);
  mpz_init (s3);
  mpz_init (m);

  for (i = 0; i < reps; i++)
    {
      xsize = urandom () % (2 * SIZE) - SIZE;
      mpz_random2 (x, xsize);
      bitindex = urandom () % SIZE;

      mpz_set (s0, x);
      bit0 = mpz_tstbit (x, bitindex);
      mpz_setbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s1, x);
      bit1 = mpz_tstbit (x, bitindex);
      mpz_clrbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s2, x);
      bit2 = mpz_tstbit (x, bitindex);
      mpz_setbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s3, x);
      bit3 = mpz_tstbit (x, bitindex);

#define FAIL(str) do { s = str; goto fail; } while (0)

      if (bit1 != 1)  FAIL ("bit1 != 1");
      if (bit2 != 0)  FAIL ("bit2 != 0");
      if (bit3 != 1)  FAIL ("bit3 != 1");

      if (bit0 == 0)
	{
	  if (mpz_cmp (s0, s1) == 0 || mpz_cmp (s0, s2) != 0 || mpz_cmp (s0, s3) == 0)
	    abort ();
	}
      else
	{
	  if (mpz_cmp (s0, s1) != 0 || mpz_cmp (s0, s2) == 0 || mpz_cmp (s0, s3) != 0)
	    abort ();
	}

      if (mpz_cmp (s1, s2) == 0 || mpz_cmp (s1, s3) != 0)
	abort ();
      if (mpz_cmp (s2, s3) == 0)
	abort ();

      mpz_ui_pow_ui (m, 2L, bitindex);
      MPZ_CHECK_FORMAT (m);
      mpz_ior (x, s2, m);
      MPZ_CHECK_FORMAT (x);
      if (mpz_cmp (x, s3) != 0)
	abort ();

      mpz_com (m, m);
      MPZ_CHECK_FORMAT (m);
      mpz_and (x, s1, m);
      MPZ_CHECK_FORMAT (x);
      if (mpz_cmp (x, s2) != 0)
	abort ();
    }

  mpz_clear (x);
  mpz_clear (s0);
  mpz_clear (s1);
  mpz_clear (s2);
  mpz_clear (s3);
  mpz_clear (m);
  return;


 fail:
  printf ("%s\n", s);
  printf ("bitindex = %lu\n", bitindex);
  printf ("x = "); mpz_out_str (stdout, -16, x); printf (" hex\n");
  exit (1);
}
//~ Note: Here, (N, T, c) = (1, 0, 0)
//~ Also, 'rop' is supposed to be already initialised (see glv_scalar.h)
void build_glvScalar(GLVScalar *rop, mpz_t k3, mpz_t aa, mpz_t bb, mpz_t Na){
	
	int j;
	mpz_t x1, x2, y1, y2, k1, k2;
	mpz_inits (x1, x2, y1, y2, k1, k2, NULL);


	mpz_mul (x1, k3, aa);
	mpz_mul (x2, k3, bb);
	mpz_neg (x2, x2);

	mpz_fdiv_q (y1, x1, Na);
	mpz_fdiv_q (y2, x2, Na);
	
	
	mpz_mul (x1, bb, y2);
	mpz_mul (k1, aa, y1);
	mpz_sub (k1, k1, x1);
	mpz_sub (k1, k3, k1);
	
	mpz_mul (x2, aa, y2);
	mpz_mul (k2, bb, y1);
	mpz_add (k2, k2, x2);
	mpz_neg (k2, k2);
	
	

	j = 0;
	while((mpz_cmp_ui (k1, 0)!=0) || (mpz_cmp_ui (k2, 0)!=0)){
		if(mpz_tstbit (k1, 0)) rop->tk1[j] = 1;
		if(mpz_tstbit (k2, 0)) rop->tk2[j] = 1;
		
		if((rop->tk1[j]==1) && (rop->tk2[j]==1)){
			if(mpz_tstbit (k1, 1)) rop->tk1[j] = -1;
			if(mpz_tstbit (k2, 1)) rop->tk2[j] = -1;
		}
		else if(rop->tk1[j] != rop->tk2[j]){
			if(mpz_tstbit (k1, 1) != mpz_tstbit (k2, 1)){
				rop->tk1[j] = -(rop->tk1[j]); 
				rop->tk2[j] = -(rop->tk2[j]);
			}
		}
		
		if(rop->tk1[j] == 1)
			mpz_sub_ui (k1, k1, 1);
		else if(rop->tk1[j] == -1)
			mpz_add_ui (k1, k1, 1);
		
		//~ Correspond to shiftRight(1)
		mpz_clrbit (k1, 0);
		mpz_divexact_ui (k1, k1, 2);
		
		if(rop->tk2[j] == 1)
			mpz_sub_ui (k2, k2, 1);
		else if(rop->tk2[j] == -1)
			mpz_add_ui (k2, k2, 1);
		
		//~ Correspond to shiftRight(1)
		mpz_clrbit (k2, 0);
		mpz_divexact_ui (k2, k2, 2);
		
		j +=1;
	}
	j -=1;

	rop->j = j;

	mpz_clears (x1, x2, y1, y2, k1, k2, NULL);
}
예제 #26
0
static PyObject *
GMPy_MPZ_pack(PyObject *self, PyObject *args)
{
    mp_bitcnt_t nbits, total_bits, tempx_bits;
    Py_ssize_t index, lst_count, i, temp_bits, limb_count;
    PyObject *lst;
    mpz_t temp;
    MPZ_Object *result, *tempx = 0;
    CTXT_Object *context = NULL;

    if (PyTuple_GET_SIZE(args) != 2) {
        TYPE_ERROR("pack() requires 'list','int' arguments");
        return NULL;
    }

    nbits = mp_bitcnt_t_From_Integer(PyTuple_GET_ITEM(args, 1));
    if (nbits == (mp_bitcnt_t)(-1) && PyErr_Occurred()) {
        return NULL;
    }

    if (!PyList_Check(PyTuple_GET_ITEM(args, 0))) {
        TYPE_ERROR("pack() requires 'list','int' arguments");
        return NULL;
    }

    if (!(result = GMPy_MPZ_New(context)))
        return NULL;

    lst = PyTuple_GET_ITEM(args, 0);
    lst_count = PyList_GET_SIZE(lst);
    total_bits = nbits * lst_count;

    if ((total_bits / lst_count) != nbits) {
        VALUE_ERROR("result too large to store in an 'mpz'");
        return NULL;
    }

    mpz_set_ui(result->z, 0);
    mpz_setbit(result->z, total_bits + (mp_bits_per_limb * 2));

    mpz_init(temp);
    mpz_set_ui(temp, 0);
    limb_count = 0;
    tempx_bits = 0;

    for (index = 0; index < lst_count; index++) {
        if (!(tempx = GMPy_MPZ_From_Integer(PyList_GetItem(lst, index), context))
            || (mpz_sgn(tempx->z) < 0)
            || (mpz_sizeinbase(tempx->z,2) > (size_t)nbits)) {
            TYPE_ERROR("pack() requires list elements be positive integers < 2^n bits");
            mpz_clear(temp);
            Py_XDECREF((PyObject*)tempx);
            Py_DECREF((PyObject*)result);
            return NULL;
        }
        mpz_mul_2exp(tempx->z, tempx->z, tempx_bits);
        mpz_add(temp, temp, tempx->z);
        tempx_bits += nbits;
        i = 0;
        temp_bits = mpz_sizeinbase(temp, 2) * mpz_sgn(temp);
        while (tempx_bits >= (mp_bitcnt_t)mp_bits_per_limb) {
            if (temp_bits > 0) {
                result->z->_mp_d[limb_count] = mpz_getlimbn(temp, i);
            }
            i += 1;
            tempx_bits -= mp_bits_per_limb;
            limb_count += 1;
            temp_bits -= mp_bits_per_limb;
        }
        if (temp_bits > 0) {
            mpz_tdiv_q_2exp(temp, temp, mp_bits_per_limb * i);
        }
        else {
            mpz_set_ui(temp, 0);
        }
        Py_DECREF((PyObject*)tempx);
    }
    result->z->_mp_d[limb_count] = mpz_getlimbn(temp, 0);
    mpz_clrbit(result->z, total_bits + (mp_bits_per_limb * 2));
    mpz_clear(temp);
    return (PyObject*)result;
}
예제 #27
0
static PyObject *
GMPy_MPZ_unpack(PyObject *self, PyObject *args)
{
    mp_bitcnt_t nbits, total_bits, guard_bit, extra_bits, temp_bits;
    Py_ssize_t index = 0, lst_count, i, lst_ptr = 0;
    PyObject *result;
    mpz_t temp;
    mp_limb_t extra = 0;
    MPZ_Object *item, *tempx = NULL;
    CTXT_Object *context = NULL;

    if (PyTuple_GET_SIZE(args) != 2) {
        TYPE_ERROR("unpack() requires 'int','int' arguments");
        return NULL;
    }

    nbits = mp_bitcnt_t_From_Integer(PyTuple_GET_ITEM(args, 1));
    if (nbits == (mp_bitcnt_t)(-1) && PyErr_Occurred()) {
        return NULL;
    }

    if (!(tempx = GMPy_MPZ_From_Integer(PyTuple_GET_ITEM(args, 0), context))) {
        TYPE_ERROR("unpack() requires 'int','int' arguments");
        return NULL;
    }

    if (mpz_sgn(tempx->z) < 0) {
        VALUE_ERROR("unpack() requires x >= 0");
        return NULL;
    }

    if (mpz_sgn(tempx->z) == 0) {
        total_bits = 0;
    }
    else {
        total_bits = mpz_sizeinbase(tempx->z, 2);
    }

    lst_count = total_bits / nbits;
    if ((total_bits % nbits) || !lst_count) {
        lst_count += 1;
    }

    if (!(result = PyList_New(lst_count))) {
        Py_DECREF((PyObject*)tempx);
        return NULL;
    }

    if (mpz_sgn(tempx->z) == 0) {
        if (!(item = GMPy_MPZ_New(context))) {
            Py_DECREF((PyObject*)tempx);
            Py_DECREF(result);
            return NULL;
        }
        mpz_set_ui(item->z, 0);
        PyList_SET_ITEM(result, 0, (PyObject*)item);
        Py_DECREF((PyObject*)tempx);
        return result;
    }

    mpz_init(temp);
    guard_bit = nbits + (2 * mp_bits_per_limb);
    extra_bits = 0;
    index = 0;

    while (lst_ptr < lst_count) {
        i = 0;
        temp_bits = 0;
        mpz_set_ui(temp, 0);
        mpz_setbit(temp, guard_bit);
        while (temp_bits + extra_bits < nbits) {
            temp->_mp_d[i++] = mpz_getlimbn(tempx->z, index++);
            temp_bits += mp_bits_per_limb;
        }
        mpz_clrbit(temp, guard_bit);
        mpz_mul_2exp(temp, temp, extra_bits);
        if (mpz_sgn(temp) == 0 && extra != 0) {
            mpz_set_ui(temp, 1);
            temp->_mp_d[0] = extra;
        }
        else {
           mpn_add_1(temp->_mp_d, temp->_mp_d, mpz_size(temp), extra);
        }
        temp_bits += extra_bits;

        while ((lst_ptr < lst_count) && (temp_bits >= nbits)) {
            if(!(item = GMPy_MPZ_New(context))) {
                mpz_clear(temp);
                Py_DECREF((PyObject*)tempx);
                Py_DECREF(result);
                return NULL;
            }
            mpz_tdiv_r_2exp(item->z, temp, nbits);
            PyList_SET_ITEM(result, lst_ptr++, (PyObject*)item);
            mpz_tdiv_q_2exp(temp, temp, nbits);
            temp_bits -= nbits;
        }
        extra = mpz_getlimbn(temp, 0);
        extra_bits = temp_bits;
    }
    Py_DECREF((PyObject*)tempx);
    mpz_clear(temp);
    return result;
}
VOID MakeSafePrime(MakePrimeParams *_pParams)
{
 // 5, 7, 11, 23, 47, 59, 83, 107, 167, 179, 227, 263, 347, 359, 383, 467, 479,
 // 503, 563, 587, 719, 839, 863, 887, 983, 1019, 1187, 1283, 1307, 1319, 1367,
 // 1439, 1487, 1523, 1619, 1823, 1907...
 const uint32_t StepVal=2;
 BOOL Success;
 UINT Bits;

 uint32_t MaxSmallPrimeSqr;
// uint32_t tmpUI;
 const clock_t clock1=clock();
 clock_t clock2;

 _pParams->Cnt[0]=0;
 _pParams->Cnt[1]=0;
 _pParams->Cnt[2]=0;
 _pParams->mSecs =0;

 UpdateLabels(_pParams);

  Bits=mpz_sizeinbase(_pParams->mpzP, 2);
  
  if(Bits>MAX_BITS_FOR_SAFE)
  { 
   return;
  }

  else if(mpz_cmp_ui(_pParams->mpzP, 5)<=0)
  {
   mpz_set_ui(_pParams->mpzP, 5);
   return;
  }

 CTrialDivisionPrimeTest*   pTrialDivisionTest =new CTrialDivisionPrimeTest();
 MaxSmallPrimeSqr=pTrialDivisionTest->GetMaxSmallPrime();
 MaxSmallPrimeSqr*=MaxSmallPrimeSqr;

 CMillerRabinTest*          pMillerRabinTest   =new CMillerRabinTest(Bits);
 CStrongLucasSelfridgeTest* pStrongLucasSelfridgeTest;

 uint32_t ulMaxBits=2*Bits + mp_bits_per_limb;
 mpz_init2(_pParams->mpzP2, ulMaxBits);

 mpz_init(_pParams->mpzP3);

 do
 {
  if(Busy==FALSE)break;

     mpz_setbit(_pParams->mpzP, 0); //Чётное
   if(_pParams->Blum)
     mpz_setbit(_pParams->mpzP, 1);

     mpz_set(_pParams->mpzP2, _pParams->mpzP);
     mpz_clrbit(_pParams->mpzP2, 0);//-1

  //TrialDivisionTest Не проверяет на 2,
  //поэтому пока не делим _pParams->mpzP2 на 2, сделаем это позже.
    // MessageBox(_pParams->hWnd, TEXT(""), TEXT(""), MB_OK);
  Success=pTrialDivisionTest->Test(_pParams->mpzP, _pParams->mpzP2);
  _pParams->Cnt[0]++;
   if(!Success){ mpz_add_ui(_pParams->mpzP, _pParams->mpzP, StepVal); continue;}
   
   //А сейчас уже надо делить на 2
   mpz_div_ui(_pParams->mpzP2, _pParams->mpzP2, 2);

  Success=pMillerRabinTest->Test(_pParams->mpzP, 14);
   if(Success)
     Success=pMillerRabinTest->Test(_pParams->mpzP2, 14);

   _pParams->Cnt[1]++;

   if(_pParams->Cnt[1]%17==0)
   {
    clock2=clock();
   _pParams->mSecs=(int)( (((float)(clock2)-(float)clock1)/CLOCKS_PER_SEC)*1000);
   }
   else if(_pParams->Cnt[1]%7==0)
   {
    UpdateLabels(_pParams);
    ProcessMessages(NULL);
   }
   

   if(!Success){mpz_add_ui(_pParams->mpzP, _pParams->mpzP, StepVal); continue;}

  pStrongLucasSelfridgeTest=new CStrongLucasSelfridgeTest(Bits);
  Success=pStrongLucasSelfridgeTest->Test(_pParams->mpzP);
  _pParams->Cnt[2]++;

   if(!Success){delete pStrongLucasSelfridgeTest; mpz_add_ui(_pParams->mpzP, _pParams->mpzP, StepVal); continue;}
  delete pStrongLucasSelfridgeTest;
  break;

 }while(1);

  clock2=clock();
  _pParams->mSecs=(int)( (((float)(clock2)-(float)clock1)/CLOCKS_PER_SEC)*1000);
  UpdateLabels(_pParams);
  ProcessMessages(NULL);

  delete  pMillerRabinTest;
  delete  pTrialDivisionTest;
  mpz_clear(_pParams->mpzP2);
  mpz_clear(_pParams->mpzP3);
 }//--//
예제 #29
0
void
mpi_clear_bit( MPI a, unsigned n )
{
    mpz_clrbit(a, n);
}