コード例 #1
0
ファイル: eu065.c プロジェクト: pbevin/euler
void eu065(char *ans) {
  int N = 99;
  mpz_t n, d, r;

  mpz_init(n);
  mpz_init(d);
  mpz_init(r);

  mpz_set_ui(n, eterm(N));
  mpz_set_ui(d, 1);

  for (int i = N-1; i >= 0; i--) {
    mpz_swap(n, d);
    int t = eterm(i);
    mpz_addmul_ui(n, d, t);
    mpz_gcd(r, n, d);
    mpz_div(n, n, r);
    mpz_div(d, d, r);
  }

  sprintf(ans, "%d", digitsum(n));

  mpz_clear(r);
  mpz_clear(d);
  mpz_clear(n);
}
コード例 #2
0
 friend const BigInteger operator/(const BigInteger& left,
         const BigInteger& right) {
     BigInteger i;
     assert(right != 0);
     mpz_div(i.integer, left.integer, right.integer);
     return i;
 }
コード例 #3
0
paillier_plaintext_t*
paillier_dec( paillier_plaintext_t* res,
							paillier_pubkey_t* pub,
							paillier_prvkey_t* prv,
							paillier_ciphertext_t* ct )
{
	if( !res )
	{
		res = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
		mpz_init(res->m);
	}
//	mpz_out_str(stdout, 10, ct->c);
	mpz_powm(res->m, ct->c, prv->lambda, pub->n_squared);
//	printf("\ndecryption\n");
//	mpz_out_str(stdout, 10, res->m);
	mpz_sub_ui(res->m, res->m, 1);
//	printf("\ndecryption\n");
//	mpz_out_str(stdout, 10, res->m);
	mpz_div(res->m, res->m, pub->n);
//	printf("\ndecryption\n");
//	mpz_out_str(stdout, 10, res->m);
	mpz_mul(res->m, res->m, prv->x);
//	printf("\ndecryption\n");
//	mpz_out_str(stdout, 10, res->m);
	//mpz_mod(res->m, res->m, pub->n);
//	printf("\ndecryption\n");
//	mpz_out_str(stdout, 10, res->m);
	return res;
}
コード例 #4
0
void
complete_prvkey( paillier_prvkey_t* prv, paillier_pubkey_t* pub )
{
	mpz_powm(prv->x, pub->n_plusone, prv->lambda, pub->n_squared);
	mpz_sub_ui(prv->x, prv->x, 1);
	mpz_div(prv->x, prv->x, pub->n);
	mpz_invert(prv->x, prv->x, pub->n);
}
コード例 #5
0
ファイル: idris_gmp.c プロジェクト: dagit/Idris-dev
VAL bigDiv(VM* vm, VAL x, VAL y) {
    mpz_t* bigint;
    VAL cl = allocate(vm, sizeof(ClosureType) + sizeof(void*));
    bigint = allocate(vm, sizeof(mpz_t));
    mpz_div(*bigint, GETMPZ(x), GETMPZ(y));
    cl -> ty = BIGINT;
    cl -> info.ptr = (void*)bigint;
    return cl;
}
コード例 #6
0
ファイル: basemath.c プロジェクト: bitwize/rscheme
obj rational_to_bignum( obj a )
{
    mpq_t a1;
    mpz_t r;
    OBJ_TO_MPQ(a1, a);
    mpz_init(r);
    mpz_div(r, mpq_numref(a1), mpq_denref(a1));
    return mpz_to_bignum(r);
}
コード例 #7
0
ファイル: idris_gmp.c プロジェクト: erkin/Idris-dev
VAL bigDiv(VM* vm, VAL x, VAL y) {
    mpz_t* bigint;
    VAL cl = allocate(vm, sizeof(ClosureType) + sizeof(void*) + 
                          sizeof(mpz_t), 0);
    bigint = (mpz_t*)(((char*)cl) + sizeof(ClosureType) + sizeof(void*));
    mpz_div(*bigint, GETMPZ(x), GETMPZ(y));
    SETTY(cl, BIGINT);
    cl -> info.ptr = (void*)bigint;
    return cl;
}
コード例 #8
0
ファイル: basemath.c プロジェクト: bitwize/rscheme
obj bignum_div( obj a, obj b )
{
    mpz_t r, a1, b1;

    OBJ_TO_MPZ(a1, a);
    OBJ_TO_MPZ(b1, b);

    mpz_init(r);
    if ( mpz_sgn(b1) == 0 ) {
        scheme_error( "dividing ~s by zero", 1, a );
    }
    mpz_div(r, a1, b1);
    return bignum_compact(r);
}
コード例 #9
0
ファイル: prho.c プロジェクト: FairSky/ggnfs
int prho(mpz_t factor1, mpz_t factor2, mpz_t n, long c, long maxIts)
/* It is assumed that the input is composite. */
{ static mpz_t a, b, oldA, oldB, tmp, tmp2;
  static int initialized=0;
  long   i, its;

  if (!(initialized)) {
    mpz_init(a); mpz_init(b); mpz_init(tmp); mpz_init(tmp2);
    mpz_init(oldA); mpz_init(oldB);
    initialized=1;
  }
  if (c<1) c=1;
  if (c>0x000000FF) c &= 0x000000FF;
  mpz_set_ui(a, 1);
  mpz_set_ui(b, 1);
  its=0;
  do {
    mpz_set(oldA, a); mpz_set(oldB, b);
    mpz_set_ui(tmp2, 1);
    for (i=25; i>0; i--) {
      mpz_mul(tmp, a, a); mpz_add_ui(tmp, tmp, c); mpz_mod(a, tmp, n);
      mpz_mul(tmp, b, b); mpz_add_ui(tmp, tmp, c); mpz_mod(b, tmp, n);
      mpz_mul(tmp, b, b); mpz_add_ui(tmp, tmp, c); mpz_mod(b, tmp, n);

      mpz_sub(tmp, a, b); mpz_mul(tmp2, tmp2, tmp); mpz_mod(tmp2, tmp2, n);
    }
    its += 25;
    mpz_gcd(tmp, tmp2, n);
  } while ((mpz_cmp_ui(tmp, 1)==0) && (its<maxIts));
  if (its >= maxIts) return -1;
  if (mpz_cmp(tmp, n) == 0) {
    mpz_set(a, oldA); mpz_set(b, oldB);
    do {
      mpz_mul(tmp, a, a); mpz_add_ui(tmp, tmp, c); mpz_mod(a, tmp, n);
      mpz_mul(tmp, b, b); mpz_add_ui(tmp, tmp, c); mpz_mod(b, tmp, n);
      mpz_mul(tmp, b, b); mpz_add_ui(tmp, tmp, c); mpz_mod(b, tmp, n);
      mpz_sub(tmp, a, b);
      mpz_gcd(tmp, tmp, n);
    } while (mpz_cmp_ui(tmp, 1)==0);
  }
  if (mpz_cmp(tmp, n) < 0) {
    mpz_set(factor1, tmp);
    mpz_div(factor2, n, factor1);
    return 0;
  }
  return -1; /* Unknown failure. */
}
コード例 #10
0
/*
 * \brief                Encrypts/decrypts a message using the RSA algorithm.
 *
 * \param result         a field to populate with the result of your RSA calculation.
 * \param message        the message to perform RSA on. (probably a cert in this case)
 * \param d              the encryption key from the key_file passed in through the
 *                       command-line arguments
 * \param n              the modulus for RSA from the modulus_file passed in through
 *                       the command-line arguments
 *
 * Fill in this function with your proj0 solution or see staff solutions.
 */
static void
perform_rsa(mpz_t result, mpz_t message, mpz_t d, mpz_t n)
{
	int hex = 16;
	mpz_t zero, one, two, tmp;
	char zero_str[] = "0";
	char one_str[] = "1";
	char two_str[] = "2";

	mpz_init(zero);
	mpz_init(one);
	mpz_init(two);
	mpz_init(tmp);

	mpz_set_str(zero, zero_str, hex);
	mpz_set_str(one, one_str, hex);
	mpz_set_str(two, two_str, hex);
	mpz_set_str(tmp, zero_str, hex);
	
	// initilize result = 1;
	mpz_add(result, zero, one);

	while (mpz_cmp(d, zero) > 0){
		mpz_mod(tmp, d, two);
		if (mpz_cmp(tmp, one) == 0) {
			// result = (result * message) % n;
			mpz_mul(tmp, result, message);
			mpz_mod(result, tmp, n);
			// d--;
			mpz_sub(d, d, one);
		}
		// d = d/2;
		mpz_div(d, d, two);
		// message = (message * message) % n;
		mpz_mul(tmp, message, message);
		mpz_mod(message, tmp, n);
	}
	mpz_clear(zero);
	mpz_clear(one);
	mpz_clear(two);
	mpz_clear(tmp);
}
コード例 #11
0
ファイル: unigcd.cpp プロジェクト: AnZhg/mU
/**
\brief 基b下整数n的长度
*/
void IntegerLength_BigBase(mpz_ptr r,mpz_ptr n,mpz_ptr b)
{
	static mpz_t nn;
	mpz_init(nn);
	mpz_set(nn,n);
	mpz_set_ui(r,0);
	while(1)
	{
		if(mpz_size(nn)!=0)
		{
			mpz_add_ui(r,r,1);
			mpz_div(nn,nn,b);
		}
		else
		{
			mpz_clear(nn);
			return ;
		}
	}
}
コード例 #12
0
paillier_plaintext_t*
paillier_dec( paillier_plaintext_t* res,
							paillier_pubkey_t* pub,
							paillier_prvkey_t* prv,
							paillier_ciphertext_t* ct )
{
	if( !res )
	{
		res = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
		mpz_init(res->m);
	}

	mpz_powm(res->m, ct->c, prv->lambda, pub->n_squared);
	mpz_sub_ui(res->m, res->m, 1);
	mpz_div(res->m, res->m, pub->n);
	mpz_mul(res->m, res->m, prv->x);
	mpz_mod(res->m, res->m, pub->n);

	return res;
}
コード例 #13
0
ファイル: div.cpp プロジェクト: dyfet/libcoimath
BN BN::operator/(const BN& div) const
{
	BN result;
	mpz_div(PTR(result.dp), BNP, REF(div.dp));
	return result;
}	
コード例 #14
0
ファイル: cracker.c プロジェクト: ctreatma/c_exercises
int main(int argc, char** argv) {
  FILE* ifp;
  FILE* ofp;

  char* nstr;

  mpz_t e, d, n;
  mpz_t p, q, t, phi;
  mpz_t one, two;
  mpz_t p2, q2;

  int l1, l2;

  l1 = 1;
  clock();

  mpz_init(e);
  mpz_init(d);
  mpz_init(n);
  mpz_init(p);
  mpz_init(q);
  mpz_init(phi);
  mpz_init(t);
  mpz_init_set_si(one, 1);
  mpz_init_set_si(two, 2);
  mpz_init(p2);
  mpz_init(q2);

  if (argc != 3) {
    printf("Bad command line.\n");
    exit(1);
  }

  ifp = fopen(argv[1], "r");
  ofp = fopen(argv[2], "w");

  mpz_inp_str(e, ifp, 10);
  mpz_inp_str(n, ifp, 10);

  mpz_set(p, two);
  while (true) {
    nstr = mpz_get_str(NULL, 10, p);
    l2 = strlen(nstr);
    if (l2 > l1) {
      printf("%d digits: %f seconds.\n", l1, clock() / ((double)CLOCKS_PER_SEC));
      l1 = l2;
    }
    free((void*)nstr);

    mpz_div(q, n, p);
    mpz_mul(t, q, p);
    if (mpz_cmp(t, n)==0)
      break;
    mpz_add(p, p, one);
  }

  mpz_sub(p2, p, one);
  mpz_sub(q2, q, one);
  mpz_mul(phi, p2, q2);
  mpz_invert(d, e, phi);

  mpz_out_str(ofp, 10, d);
  fprintf(ofp, "\n\n");
  mpz_out_str(ofp, 10, n);

  return 0;
}
コード例 #15
0
ファイル: damgard_jurik.cpp プロジェクト: jianyu-m/OnionOram
void damgard_jurik_function_l(mpz_t result ,mpz_t b, mpz_t n) {
    mpz_sub_ui(result, b, 1);
    mpz_div(result, result, n);
}
コード例 #16
0
int shankSquares(mpz_t *n)
{
	mpz_t myN, constA, constB, tmp, tmp2;
	mpz_t Pi, Qi, Plast, Qlast, Qnext, bi;
	long counter = 1;
	int status = FAIL;
	
	printf("[INFO ] Trying shank squares\n");


	mpz_init_set(myN, *n);

	mpz_init(tmp);	mpz_init(tmp2);
	mpz_init(bi);	mpz_init(Qnext);
	mpz_init(Pi);

	mpz_mul_ui(tmp, myN, SHANKQUAREK); // constA = k*N
	mpz_init_set(constA, tmp);

	mpz_sqrt(tmp, constA);	// constB = floor(sqrt(constA))
	mpz_init_set(constB, tmp);

	mpz_init_set(Plast, constB);


	mpz_pow_ui(tmp, Plast, 2);	// Qi = (constA) - (Pi**2)
	mpz_sub(tmp, constA, tmp);
	mpz_init_set(Qi, tmp);

	
	mpz_init_set_ui(Qlast, 1);


	while (counter < SHANKQUAREMAX)
	{

		mpz_add(tmp, constB, Plast);	//bi = floor( (constB) + (Plast) / Qi )
		mpz_fdiv_q(bi, tmp, Qi);

		mpz_mul(tmp, bi, Qi);			//Pi = (bi * Qi) - (Plast)
		mpz_sub(Pi, tmp, Plast);

		mpz_sub(tmp, Plast, Pi);		//Qnext = Qlast + (bi * (Plast - Pi))
		mpz_mul(tmp, tmp, bi);
		mpz_add(Qnext, Qlast, tmp);

		if (mpz_perfect_square_p(Qi) != 0 && counter % 2 == 0)
		{
			break;
		}
		else
		{
			mpz_set(Plast, Pi);
			mpz_set(Qlast, Qi);
			mpz_set(Qi, Qnext);	
		}

		counter += 1;
	}


	mpz_sub(tmp, constB, Plast);	//bi = floor( ( constB - Plast ) / sqrt(Qi) )
	mpz_sqrt(tmp2, Qi);
	mpz_fdiv_q(bi, tmp, tmp2);

	mpz_sqrt(tmp, Qi);				//Plast = (bi * sqrt(Qi)) + Plast
	mpz_mul(tmp, tmp, bi);
	mpz_add(Plast, tmp, Plast);

	mpz_sqrt(Qlast, Qi);

	mpz_pow_ui(tmp2, Plast, 2);		//Qnext = ((constA) - Plast**2) / Qlast
	mpz_sub(tmp, constA, tmp2);
	mpz_div(Qnext, tmp, Qlast);

	mpz_set(Qi, Qnext);

	counter = 0;

	while (counter < SHANKQUAREMAX)
	{
		mpz_add(tmp, constB, Plast);	//bi = floor( ( constB + Plast ) / Qi )
		mpz_fdiv_q(bi, tmp, Qi);

		mpz_mul(tmp, bi, Qi);			//Pi = (bi*Qi) - Plast
		mpz_sub(Pi, tmp, Plast);

		mpz_sub(tmp, Plast, Pi);		//Qnext = Qlast + (bi * (Plast - Pi))
		mpz_mul(tmp, tmp, bi);
		mpz_add(Qnext, Qlast, tmp);

		if (mpz_cmp(Pi, Plast) == 0)
		{
			break;
		}

		mpz_set(Plast, Pi);
		mpz_set(Qlast, Qi);
		mpz_set(Qi, Qnext);

		counter += 1;
	}

	mpz_gcd(tmp, myN, Pi);

	if (mpz_cmp_ui(tmp, 1) != 0 && mpz_cmp(tmp, myN) != 0)
	{
		printWin(&tmp, "Shanks squares");
		status = WIN;
	}

	mpz_clear(myN);		mpz_clear(constA);
	mpz_clear(constB);	mpz_clear(tmp);		mpz_clear(tmp2);
	mpz_clear(Pi);		mpz_clear(Qi);		mpz_clear(Plast);
	mpz_clear(Qlast);	mpz_clear(Qnext);	mpz_clear(bi);

	return status;

}
コード例 #17
0
 BigInteger &operator/=(const BigInteger &i) {
     assert(i.integer != 0);
     mpz_div(integer, integer, i.integer);
     return *this;
 }
コード例 #18
0
ファイル: rsa.cpp プロジェクト: dreamsxin/ultimatepp
static void derive_rsa_keys(MP_INT *n, MP_INT *e, MP_INT *d, MP_INT *u,

                         MP_INT *p, MP_INT *q,

                         unsigned int ebits)

{

  MP_INT p_minus_1, q_minus_1, aux, phi, G, F;



  assert(mpz_cmp(p, q) < 0);



  mpz_init(&p_minus_1);

  mpz_init(&q_minus_1);

  mpz_init(&aux);

  mpz_init(&phi);

  mpz_init(&G);

  mpz_init(&F);



  /* Compute p-1 and q-1. */

  mpz_sub_ui(&p_minus_1, p, 1);

  mpz_sub_ui(&q_minus_1, q, 1);



  /* phi = (p - 1) * (q - 1); the number of positive integers less than p*q

     that are relatively prime to p*q. */

  mpz_mul(&phi, &p_minus_1, &q_minus_1);



  /* G is the number of "spare key sets" for a given modulus n.  The smaller

     G is, the better.  The smallest G can get is 2. */

  mpz_gcd(&G, &p_minus_1, &q_minus_1);



  if (rsa_verbose)

    {

      if (mpz_cmp_ui(&G, 100) >= 0)

       {

         fprintf(stderr, "Warning: G=");

         mpz_out_str(stdout, 10, &G);

         fprintf(stderr, " is large (many spare key sets); key may be bad!\n");

       }

    }



  /* F = phi / G; the number of relative prime numbers per spare key set. */

  mpz_div(&F, &phi, &G);



  /* Find a suitable e (the public exponent). */

  mpz_set_ui(e, 1);

  mpz_mul_2exp(e, e, ebits);

  mpz_sub_ui(e, e, 1); /* make lowest bit 1, and substract 2. */

  /* Keep adding 2 until it is relatively prime to (p-1)(q-1). */

  do

    {

      mpz_add_ui(e, e, 2);

      mpz_gcd(&aux, e, &phi);

    }

  while (mpz_cmp_ui(&aux, 1) != 0);



  /* d is the multiplicative inverse of e, mod F.  Could also be mod

     (p-1)(q-1); however, we try to choose the smallest possible d. */

  mpz_mod_inverse(d, e, &F);



  /* u is the multiplicative inverse of p, mod q, if p < q.  It is used

     when doing private key RSA operations using the chinese remainder

     theorem method. */

  mpz_mod_inverse(u, p, q);



  /* n = p * q (the public modulus). */

  mpz_mul(n, p, q);



  /* Clear auxiliary variables. */

  mpz_clear(&p_minus_1);

  mpz_clear(&q_minus_1);

  mpz_clear(&aux);

  mpz_clear(&phi);

  mpz_clear(&G);

  mpz_clear(&F);

}
コード例 #19
0
ファイル: miner2.cpp プロジェクト: valliammal/jhPrimeminer
bool BitcoinMiner2_mineProbableChain(primecoinBlock_t* block, mpz_class& mpzFixedMultiplier, bool& fNewBlock, unsigned int& nTriedMultiplier, unsigned int& nProbableChainLength, 
										 unsigned int& nTests, unsigned int& nPrimesHit, sint32 threadIndex, mpz_class& mpzHash, unsigned int nPrimorialMultiplier)
{
	mpz_class mpzChainOrigin;
	mpz_class mpzFinalFixedMultiplier = mpzFixedMultiplier * mpzHash;
	mpz_class mpzTemp;
	uint32 nTime = GetTickCount();
	cSieve_prepare(mpzFinalFixedMultiplier, block->nBits>>24);
	nTime = GetTickCount()-nTime;
	//printf("cSieve prep time: %d\n", nTime);

	unsigned int nPrimorialSeq = 0;
	while (vPrimes[nPrimorialSeq + 1] <= nPrimorialMultiplier)
		nPrimorialSeq++;
	// Allocate GMP variables for primality tests
	CPrimalityTestParams testParams(block->nBits, nPrimorialSeq);
	{
		unsigned long lDivisor = 1;
		unsigned int i;
		testParams.vFastDivSeq.push_back(nPrimorialSeq);
		for (i = 1; i <= nFastDivPrimes; i++)
		{
			// Multiply primes together until the result won't fit an unsigned long
			if (lDivisor < ULONG_MAX / vPrimes[nPrimorialSeq + i])
				lDivisor *= vPrimes[nPrimorialSeq + i];
			else
			{
				testParams.vFastDivisors.push_back(lDivisor);
				testParams.vFastDivSeq.push_back(nPrimorialSeq + i);
				lDivisor = 1;
			}
		}

		// Finish off by multiplying as many primes as possible
		while (lDivisor < ULONG_MAX / vPrimes[nPrimorialSeq + i])
		{
			lDivisor *= vPrimes[nPrimorialSeq + i];
			i++;
		}
		testParams.vFastDivisors.push_back(lDivisor);
		testParams.vFastDivSeq.push_back(nPrimorialSeq + i);
		testParams.nFastDivisorsSize = testParams.vFastDivisors.size();
	}
	// References to counters;
	unsigned int& nChainLengthCunningham1 = testParams.nChainLengthCunningham1;
	unsigned int& nChainLengthCunningham2 = testParams.nChainLengthCunningham2;
	unsigned int& nChainLengthBiTwin = testParams.nChainLengthBiTwin;

	uint32 debugStats_primes = 0;
	uint32 debugStats_multipliersTested = 0;
	
	while( block->serverData.blockHeight == jhMiner_getCurrentWorkBlockHeight(block->threadIndex) )
	{
		uint32 sieveFlags;
		uint32 multiplier = cSieve_findNextMultiplier(&sieveFlags);
		if( multiplier == 0 )
		{
			// mix in next layer
			//printf("Layer finished [%d]\n", cSieve->currentSieveLayerIdx);
			if( cSieve_sieveNextLayer() == false )
				break;
			mpzFinalFixedMultiplier = cSieve->mpzFixedMultiplier;
			//printf("[%02d] debugStats_multipliersTested: %d\n", cSieve->currentSieveLayerIdx, debugStats_multipliersTested);
			//printf("[%02d] debugStats_primes: %d\n", cSieve->currentSieveLayerIdx, debugStats_primes);
			//double primality = (double)debugStats_primes / (double)debugStats_multipliersTested;
			//printf("[%02d] debugStats_primality: %lf\n", cSieve->currentSieveLayerIdx, primality);
			debugStats_primes = 0;
			debugStats_multipliersTested = 0;
			continue;
		}
		 
		//// test for sieve bugs C1
		//if( (sieveFlags&SIEVE_FLAG_C1_COMPOSITE)==0 && (rand()%10)==0 )
		//{
		//	// test c1
		//	for(uint32 lt=0; lt<cSieve->chainLength; lt++)
		//	{
		//		uint32 aMult = 1<<lt;
		//		mpzChainOrigin = mpzFinalFixedMultiplier * multiplier * aMult - 1;	
		//		for(uint32 f=0; f<cSieve->numPrimeFactors; f++)
		//		{
		//			uint32 mod = mpz_mod_ui(mpzTemp.get_mpz_t(), mpzChainOrigin.get_mpz_t(), vPrimes[f]);
		//			if( mod == 0 )
		//				printf("c1 div by %d possible\n", vPrimes[f]);//__debugbreak();
		//		}
		//	}
		//}
		//// test for sieve bugs C2
		//if( (sieveFlags&SIEVE_FLAG_C2_COMPOSITE)==0 && (rand()%10)==0 )
		//{
		//	// test c1
		//	for(uint32 lt=0; lt<cSieve->chainLength; lt++)
		//	{
		//		uint32 aMult = 1<<lt;
		//		mpzChainOrigin = mpzFinalFixedMultiplier * multiplier * aMult + 1;	
		//		for(uint32 f=0; f<cSieve->numPrimeFactors; f++)
		//		{
		//			uint32 mod = mpz_mod_ui(mpzTemp.get_mpz_t(), mpzChainOrigin.get_mpz_t(), vPrimes[f]);
		//			if( mod == 0 )
		//				printf("c2 div by %d possible\n", vPrimes[f]);//__debugbreak();
		//		}
		//	}
		//}
		// test for sieve bugs BT
		//if( (sieveFlags&SIEVE_FLAG_BT_COMPOSITE)==0 )
		//{
		//	// test c1
		//	mpzChainOrigin = mpzFinalFixedMultiplier * multiplier + 1;	
		//	for(uint32 f=0; f<cSieve->numPrimeFactors; f++)
		//	{
		//		uint32 mod = mpz_mod_ui(mpzTemp.get_mpz_t(), mpzChainOrigin.get_mpz_t(), vPrimes[f]);
		//		if( mod == 0 )
		//			printf("bt-c2 div by %d possible\n", vPrimes[f]);
		//	}
		//	// test c2
		//	mpzChainOrigin = mpzFinalFixedMultiplier * multiplier - 1;	
		//	for(uint32 f=0; f<cSieve->numPrimeFactors; f++)
		//	{
		//		uint32 mod = mpz_mod_ui(mpzTemp.get_mpz_t(), mpzChainOrigin.get_mpz_t(), vPrimes[f]);
		//		if( mod == 0 )
		//			printf("bt-c2 div by %d possible\n", vPrimes[f]);
		//	}
		//}

		//mpzChainOrigin = mpzFinalFixedMultiplier * multiplier;		
		mpz_mul_ui(mpzChainOrigin.get_mpz_t(), mpzFinalFixedMultiplier.get_mpz_t(), multiplier);
		nChainLengthCunningham1 = 0;
		nChainLengthCunningham2 = 0;
		nChainLengthBiTwin = 0;

		bool canSubmitAsShare = ProbablePrimeChainTestFast2(mpzChainOrigin, testParams, sieveFlags, multiplier);
		nProbableChainLength = max(max(nChainLengthCunningham1, nChainLengthCunningham2), nChainLengthBiTwin);

		if( nProbableChainLength >= 0x01000000 )
			debugStats_primes++;
		debugStats_multipliersTested++;
		//bool canSubmitAsShare = ProbablePrimeChainTestFast(mpzChainOrigin, testParams);
		//CBigNum bnChainOrigin;
		//bnChainOrigin.SetHex(mpzChainOrigin.get_str(16));
		//bool canSubmitAsShare = ProbablePrimeChainTestBN(bnChainOrigin, block->serverData.nBitsForShare, false, nChainLengthCunningham1, nChainLengthCunningham2, nChainLengthBiTwin);
		


		if( nProbableChainLength >= 0x04000000 )
		{
			sint32 chainDif = (nProbableChainLength>>24) - 7;
			primeStats.nChainHit += pow(8, (float)chainDif);
			//primeStats.nChainHit += pow(8, ((float)((double)nProbableChainLength  / (double)0x1000000))-7.0);
			//primeStats.nChainHit += pow(8, floor((float)((double)nProbableChainLength  / (double)0x1000000)) - 7);
			nTests = 0;
			primeStats.fourChainCount ++;
			if (nProbableChainLength >= 0x5000000)
			{
				primeStats.fiveChainCount ++;
				if (nProbableChainLength >= 0x6000000)
				{
					primeStats.sixChainCount ++;
					if (nProbableChainLength >= 0x7000000)
						primeStats.sevenChainCount ++;
				}
			}
		}
		//if( nBitsGen >= 0x03000000 )
		//	printf("%08X\n", nBitsGen);
		primeStats.primeChainsFound++;
		//if( nProbableChainLength > 0x03000000 )
		//	primeStats.qualityPrimesFound++;
		if( nProbableChainLength > primeStats.bestPrimeChainDifficulty )
			primeStats.bestPrimeChainDifficulty = nProbableChainLength;
		
		if(nProbableChainLength >= block->serverData.nBitsForShare)
		{
			// note: mpzPrimeChainMultiplier does not include the blockHash multiplier
			mpz_div(block->mpzPrimeChainMultiplier.get_mpz_t(), mpzChainOrigin.get_mpz_t(), mpzHash.get_mpz_t());
			//mpz_lsh(block->mpzPrimeChainMultiplier.get_mpz_t(), mpzFixedMultiplier.get_mpz_t(), multiplier);
			// update server data
			block->serverData.client_shareBits = nProbableChainLength;
			// generate block raw data
			uint8 blockRawData[256] = {0};
			memcpy(blockRawData, block, 80);
			uint32 writeIndex = 80;
			sint32 lengthBN = 0;
			CBigNum bnPrimeChainMultiplier;
			bnPrimeChainMultiplier.SetHex(block->mpzPrimeChainMultiplier.get_str(16));
			std::vector<unsigned char> bnSerializeData = bnPrimeChainMultiplier.getvch();
			lengthBN = bnSerializeData.size();
			*(uint8*)(blockRawData+writeIndex) = (uint8)lengthBN; // varInt (we assume it always has a size low enough for 1 byte)
			writeIndex += 1;
			memcpy(blockRawData+writeIndex, &bnSerializeData[0], lengthBN);
			writeIndex += lengthBN;	
			// switch endianness
			for(uint32 f=0; f<256/4; f++)
			{
				*(uint32*)(blockRawData+f*4) = _swapEndianessU32(*(uint32*)(blockRawData+f*4));
			}
			time_t now = time(0);
			struct tm * timeinfo;
			timeinfo = localtime (&now);
			char sNow [80];
			strftime (sNow, 80, "%x - %X",timeinfo);

			printf("%s - SHARE FOUND !!! (Th#: %u Multiplier: %d Layer: %d) ---  DIFF: %f    %s    %s\n", 
				sNow, threadIndex, multiplier, cSieve->currentSieveLayerIdx, (float)((double)nProbableChainLength  / (double)0x1000000), 
				nProbableChainLength >= 0x6000000 ? ">6":"", nProbableChainLength >= 0x7000000 ? ">7":"");

			// submit this share
			if (jhMiner_pushShare_primecoin(blockRawData, block))
				primeStats.foundShareCount ++;
			//printf("Probable prime chain found for block=%s!!\n  Target: %s\n  Length: (%s %s %s)\n", block.GetHash().GetHex().c_str(),TargetToString(block.nBits).c_str(), TargetToString(nChainLengthCunningham1).c_str(), TargetToString(nChainLengthCunningham2).c_str(), TargetToString(nChainLengthBiTwin).c_str());
			//nProbableChainLength = max(max(nChainLengthCunningham1, nChainLengthCunningham2), nChainLengthBiTwin);
			// since we are using C structs here we have to make sure the memory for the CBigNum in the block is freed again
			//delete *psieve;
			//*psieve = NULL;
			//block->bnPrimeChainMultiplier = NULL;
			RtlZeroMemory(blockRawData, 256);
			//delete *psieve;
			//*psieve = NULL;
			// dont quit if we find a share, there could be other shares in the remaining prime candidates
			nTests = 0;   // tehere is a good chance to find more shares so search a litle more.
			//block->nonce++;
			//return true;
			//break;
			//if (multipleShare)
		}
	}
コード例 #20
0
/**
 * entry point of the program.
 *
 * @function   main
 *
 * @date       2016-01-15
 *
 * @revision   none
 *
 * @designer   Eric Tsang
 *
 * @programmer Eric Tsang
 *
 * @note
 *
 * sets up synchronization primitives, spawns worker threads, generates tasks
 *   for workers, receives results from workers, waits for workers to terminate,
 *   writes results to a file, and stdout.
 *
 * @signature  int main(int argc,char** argv)
 *
 * @param      argc number of command line arguments
 * @param      argv array of c strings of command line arguments
 *
 * @return     status code.
 */
int main(int argc,char** argv)
{
    // parse command line arguments
    if (argc != 4)
    {
        fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n",argv[0]);
        return 1;
    }
    if(mpz_set_str(prime.value,argv[1],10) == -1)
    {
        fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n",argv[0]);
        return 1;
    }
    int logfile = open(argv[2],O_CREAT|O_WRONLY|O_APPEND);
    FILE* logFileOut = fdopen(logfile,"w");
    if(logfile == -1 || errno)
    {
        fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\nerror occurred: ",argv[0]);
        perror(0);
        return 1;
    }
    unsigned int numWorkers = atoi(argv[3]);
    if (numWorkers <= 0)
    {
        fprintf(stderr,"usage: %s [integer] [path to log file] [num workers]\n num workers must be larger than or equal to 1",argv[0]);
        return 1;
    }

    // set up synchronization primitives
    for(register unsigned int i; i < numWorkers*MAX_PENDING_TASKS_PER_WORKER; ++i)
    {
        tasksNotFullSem.post();
    }

    // get start time
    long startTime = current_timestamp();

    // create the worker threads
    std::vector<pthread_t> workers;
    for(register unsigned int i = 0; i < numWorkers; ++i)
    {
        pthread_t worker;
        pthread_create(&worker,0,worker_routine,0);
        workers.push_back(worker);
    }

    // create tasks and place them into the tasks vector
    {
        Number prevPercentageComplete;
        Number percentageComplete;
        Number tempLoBound;
        Number loBound;

        for(mpz_set_ui(loBound.value,1);
                mpz_cmp(loBound.value,prime.value) <= 0;
                mpz_add_ui(loBound.value,loBound.value,MAX_NUMBERS_PER_TASK))
        {
            // calculate and print percentage complete
            mpz_set(prevPercentageComplete.value,percentageComplete.value);
            mpz_mul_ui(tempLoBound.value,loBound.value,100);
            mpz_div(percentageComplete.value,tempLoBound.value,prime.value);
            if(mpz_cmp(prevPercentageComplete.value,percentageComplete.value) != 0)
            {
                gmp_fprintf(stdout,"%Zd%\n",percentageComplete.value);
                gmp_fprintf(logFileOut,"%Zd%\n",percentageComplete.value);
            }

            // insert the task into the task queue once there is room
            Number* newNum = new Number();
            mpz_set(newNum->value,loBound.value);
            tasksNotFullSem.wait();
            Lock scopelock(&taskAccess.sem);
            tasks.push_back(newNum);
        }
    }
    allTasksProduced = true;

    // join all worker threads
    for(register unsigned int i = 0; i < numWorkers; ++i)
    {
        void* unused;
        pthread_join(workers[i],&unused);
    }

    // get end time
    long endTime = current_timestamp();

    // print out calculation results
    std::sort(results.begin(),results.end(),[](Number* i,Number* j)
    {
        return mpz_cmp(i->value,j->value) < 0;
    });
    fprintf(stdout,"factors: ");
    fprintf(logFileOut,"factors: ");
    for(register unsigned int i = 0; i < results.size(); ++i)
    {
        gmp_fprintf(stdout,"%s%Zd",i?", ":"",results[i]->value);
        gmp_fprintf(logFileOut,"%s%Zd",i?", ":"",results[i]->value);
        delete results[i];
    }
    fprintf(stdout,"\n");
    fprintf(logFileOut,"\n");

    // print out execution results
    fprintf(stdout,"total runtime: %lums\n",endTime-startTime);
    fprintf(logFileOut,"total runtime: %lums\n",endTime-startTime);

    // release system resources
    fclose(logFileOut);
    close(logfile);

    return 0;
}
コード例 #21
0
ファイル: div.cpp プロジェクト: dyfet/libcoimath
BN& BN::operator/=(const BN& div)
{
	BN tmp(*this);
	mpz_div(BNP, REF(tmp.dp), REF(div.dp));
	return *this;
}