Пример #1
0
int
ot_np_recv(struct state *st, void *choices, int nchoices, int maxlength, int N,
           void *out,
           ot_choice_reader ot_choice_reader, ot_msg_writer ot_msg_writer)
{
    mpz_t gr, pk0, pks;
    mpz_t *Cs = NULL, *ks = NULL;
    char buf[field_size], *from = NULL, *msg = NULL;
    int err = 0;
    double start, end;

#ifdef AES_HW
    fprintf(stderr, "OT-NP: Using AESNI\n");
#endif
#ifdef SHA
    fprintf(stderr, "OT-NP: Using SHA-1\n");
#endif

    mpz_inits(gr, pk0, pks, NULL);

    msg = (char *) ot_malloc(sizeof(char) * maxlength);
    if (msg == NULL)
        ERROR;
    from = (char *) ot_malloc(sizeof(char) * maxlength);
    if (from == NULL)
        ERROR;
    Cs = (mpz_t *) ot_malloc(sizeof(mpz_t) * (N - 1));
    if (Cs == NULL)
        ERROR;
    for (int i = 0; i < N - 1; ++i) {
        mpz_init(Cs[i]);
    }
    ks = (mpz_t *) ot_malloc(sizeof(mpz_t) * nchoices);
    if (ks == NULL)
        ERROR;
    for (int j = 0; j < nchoices; ++j) {
        mpz_init(ks[j]);
    }

#ifdef AES_HW
    AES_KEY key;
    AES_set_encrypt_key((unsigned char *) "abcd", 128, &key);
#endif

    // get g^r from sender
    start = current_time();
    if (recvall(st->sockfd, buf, sizeof buf) == -1)
        ERROR;
    array_to_mpz(gr, buf, sizeof buf);
    end = current_time();
    fprintf(stderr, "Get g^r from sender: %f\n", end - start);

    // get Cs from sender
    start = current_time();
    for (int i = 0; i < N - 1; ++i) {
        if (recvall(st->sockfd, buf, sizeof buf) == -1)
            ERROR;
        array_to_mpz(Cs[i], buf, sizeof buf);
    }
    end = current_time();
    fprintf(stderr, "Get Cs from sender: %f\n", end - start);

    start = current_time();
    for (int j = 0; j < nchoices; ++j) {
        long choice;

        choice = ot_choice_reader(choices, j);
        // choose random k
        mpz_urandomb(ks[j], st->p.rnd, sizeof buf * 8);
        mpz_mod(ks[j], ks[j], st->p.q);
        // compute pks = g^k
        mpz_powm(pks, st->p.g, ks[j], st->p.p);
        // compute pk0 = C_1 / g^k regardless of whether our choice is 0 or 1 to
        // avoid a potential side-channel attack
        (void) mpz_invert(pk0, pks, st->p.p);
        mpz_mul(pk0, pk0, Cs[0]);
        mpz_mod(pk0, pk0, st->p.p);
        mpz_set(pk0, choice == 0 ? pks : pk0);
        mpz_to_array(buf, pk0, sizeof buf);
        // send pk0 to sender
        if (sendall(st->sockfd, buf, sizeof buf) == -1)
            ERROR;
    }
    end = current_time();
    fprintf(stderr, "Send pk0s to sender: %f\n", end - start);

    for (int j = 0; j < nchoices; ++j) {
        long choice;

        choice = ot_choice_reader(choices, j);

        // compute decryption key (g^r)^k
        mpz_powm(ks[j], gr, ks[j], st->p.p);


        for (int i = 0; i < N; ++i) {
            mpz_to_array(buf, ks[j], sizeof buf);
            // get H xor M0 from sender
            if (recvall(st->sockfd, msg, maxlength) == -1)
                ERROR;

#ifdef AES_HW
            if (AES_encrypt_message((unsigned char *) buf, sizeof buf,
                                    (unsigned char *) from, maxlength, &key))
                ERROR;
#endif
#ifdef SHA
            (void) memset(from, '\0', maxlength);
            sha1_hash(from, maxlength, i, (unsigned char *) buf, sizeof buf);
#endif

            xorarray((unsigned char *) msg, maxlength,
                     (unsigned char *) from, maxlength);

            if (i == choice) {
                ot_msg_writer(out, j, msg, maxlength);
            }
        }
    }

 cleanup:
    mpz_clears(gr, pk0, pks, NULL);

    if (ks) {
        for (int j = 0; j < nchoices; ++j) {
            mpz_clear(ks[j]);
        }
        ot_free(ks);
    }
    if (Cs) {
        for (int i = 0; i < N - 1; ++i)
            mpz_clear(Cs[i]);
        ot_free(Cs);
    }
    if (msg)
        ot_free(msg);
    if (from)
        ot_free(from);

    return err;
}
Пример #2
0
// I could generalize this for all fields, but is there any point?
void field_curve_set_quotient_cmp(field_ptr c, mpz_t quotient_cmp) {
	curve_data_ptr cdp = (curve_data_ptr)c->data;
  cdp->quotient_cmp = (mpz_ptr)pbc_malloc(sizeof(mpz_t));
  mpz_init(cdp->quotient_cmp);
  mpz_set(cdp->quotient_cmp, quotient_cmp);
}
Пример #3
0
C_BigInt::C_BigInt (const char * inString, const int32_t inBase, bool & outOk) :
mGMPint () {
  mpz_init (mGMPint) ;
  const int r = mpz_set_str (mGMPint, inString, inBase) ;
  outOk = r == 0 ;
}
Пример #4
0
static void
check_for_zero ()
{
  /* Check that 0 is unsigned! */
  mpq_t q;
  mpz_t z;
  mpfr_t x;
  int r;
  mpfr_sign_t i;

  mpfr_init (x);
  mpz_init (z);
  mpq_init (q);

  mpz_set_ui (z, 0);
  mpq_set_ui (q, 0, 1);

  MPFR_SET_ZERO (x);
  for(r = 0 ; r < GMP_RND_MAX ; r++)
    {
      for (i = MPFR_SIGN_NEG ; i <= MPFR_SIGN_POS ;
           i+=MPFR_SIGN_POS-MPFR_SIGN_NEG)
        {
          MPFR_SET_SIGN(x, i);
          mpfr_add_z (x, x, z, (mp_rnd_t) r);
          if (!MPFR_IS_ZERO(x) || MPFR_SIGN(x)!=i)
            {
              printf("GMP Zero errors for add_z & rnd=%s & s=%d\n",
                     mpfr_print_rnd_mode ((mp_rnd_t) r), i);
              mpfr_dump (x);
              exit (1);
            }
          mpfr_sub_z (x, x, z, (mp_rnd_t) r);
          if (!MPFR_IS_ZERO(x) || MPFR_SIGN(x)!=i)
            {
              printf("GMP Zero errors for sub_z & rnd=%s & s=%d\n",
                     mpfr_print_rnd_mode ((mp_rnd_t) r), i);
              mpfr_dump (x);
              exit (1);
            }
          mpfr_mul_z (x, x, z, (mp_rnd_t) r);
          if (!MPFR_IS_ZERO(x) || MPFR_SIGN(x)!=i)
            {
              printf("GMP Zero errors for mul_z & rnd=%s & s=%d\n",
                     mpfr_print_rnd_mode ((mp_rnd_t) r), i);
              mpfr_dump (x);
              exit (1);
            }
          mpfr_add_q (x, x, q, (mp_rnd_t) r);
          if (!MPFR_IS_ZERO(x) || MPFR_SIGN(x)!=i)
            {
              printf("GMP Zero errors for add_q & rnd=%s & s=%d\n",
                     mpfr_print_rnd_mode ((mp_rnd_t) r), i);
              mpfr_dump (x);
              exit (1);
            }
          mpfr_sub_q (x, x, q, (mp_rnd_t) r);
          if (!MPFR_IS_ZERO(x) || MPFR_SIGN(x)!=i)
            {
              printf("GMP Zero errors for sub_q & rnd=%s & s=%d\n",
                     mpfr_print_rnd_mode ((mp_rnd_t) r), i);
              mpfr_dump (x);
              exit (1);
             }
        }
    }

  mpq_clear (q);
  mpz_clear (z);
  mpfr_clear (x);
}
Пример #5
0
static void
test_genericz (mp_prec_t p0, mp_prec_t p1, unsigned int N,
               int (*func)(mpfr_ptr, mpfr_srcptr, mpz_srcptr, mp_rnd_t),
               const char *op)
{
  mp_prec_t prec;
  mpfr_t arg1, dst_big, dst_small, tmp;
  mpz_t  arg2;
  mp_rnd_t rnd;
  int inexact, compare, compare2;
  unsigned int n;

  mpfr_inits (arg1, dst_big, dst_small, tmp, (void *) 0);
  mpz_init (arg2);

  for (prec = p0; prec <= p1; prec++)
    {
      mpfr_set_prec (arg1, prec);
      mpfr_set_prec (tmp, prec);
      mpfr_set_prec (dst_small, prec);

      for (n=0; n<N; n++)
        {
          mpfr_urandomb (arg1, RANDS);
          mpz_urandomb (arg2, RANDS, 1024);
          rnd = (mp_rnd_t) RND_RAND ();
          mpfr_set_prec (dst_big, 2*prec);
          compare = func(dst_big, arg1, arg2, rnd);
          if (mpfr_can_round (dst_big, 2*prec, rnd, rnd, prec))
            {
              mpfr_set (tmp, dst_big, rnd);
              inexact = func(dst_small, arg1, arg2, rnd);
              if (mpfr_cmp (tmp, dst_small))
                {
                  printf ("Results differ for prec=%u rnd_mode=%s and %s_z:\n"
                          "arg1=",
                          (unsigned) prec, mpfr_print_rnd_mode (rnd), op);
                  mpfr_print_binary (arg1);
                  printf("\narg2=");
                  mpz_out_str (stdout, 2, arg2);
                  printf ("\ngot      ");
                  mpfr_dump (dst_small);
                  printf ("expected ");
                  mpfr_dump (tmp);
                  printf ("approx   ");
                  mpfr_dump (dst_big);
                  exit (1);
                }
              compare2 = mpfr_cmp (tmp, dst_big);
              /* if rounding to nearest, cannot know the sign of t - f(x)
                 because of composed rounding: y = o(f(x)) and t = o(y) */
              if (compare * compare2 >= 0)
                compare = compare + compare2;
              else
                compare = inexact; /* cannot determine sign(t-f(x)) */
              if (((inexact == 0) && (compare != 0)) ||
                  ((inexact > 0) && (compare <= 0)) ||
                  ((inexact < 0) && (compare >= 0)))
                {
                  printf ("Wrong inexact flag for rnd=%s and %s_z:\n"
                          "expected %d, got %d\n",
                          mpfr_print_rnd_mode (rnd), op, compare, inexact);
                  printf ("\narg1="); mpfr_print_binary (arg1);
                  printf ("\narg2="); mpz_out_str(stdout, 2, arg2);
                  printf ("\ndstl="); mpfr_print_binary (dst_big);
                  printf ("\ndsts="); mpfr_print_binary (dst_small);
                  printf ("\ntmp ="); mpfr_dump (tmp);
                  exit (1);
                }
            }
        }
    }

  mpz_clear (arg2);
  mpfr_clears (arg1, dst_big, dst_small, tmp, (void *) 0);
}
Пример #6
0
void sccwriter::write_code( Expr* code, std::ostream& os, int ind, const char* retModStr, int opts )
{
  std::string retModString;
  std::string incString;
  if ( retModStr )
  {
    retModString = std::string( retModStr );
    retModString.append( " = " );
    incString = std::string( retModStr );
    incString.append( "->inc();" );
  }
  switch( code->getclass() )
  {
  case INT_EXPR:
    {
      indent( os, ind );
      os << retModString.c_str();
      os << "new IntExpr( " << mpz_get_si( ((IntExpr*)code)->n ) << " );" << std::endl;
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  case RAT_EXPR:
    {
      mpz_t num, den;
      mpz_init(num);
      mpz_init(den);
      mpq_get_num( num, ((RatExpr*)code)->n );
      mpq_get_den( den, ((RatExpr*)code)->n );
      indent( os, ind );
      os << retModString.c_str();
      os << "new RatExpr( " << mpz_get_si( num ) << ", " << mpz_get_si( den ) << " );" << std::endl;
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  case SYMS_EXPR:
    {
      //if it is a variable, simply write it to buffer
      if( is_var( ((SymSExpr*)code)->s ) )
      {
        indent( os, ind );
        os << retModString.c_str();
        write_variable( ((SymSExpr*)code)->s.c_str(), os );
        os << ";" << std::endl;  
      }
      else  //else must look at symbol lookup table
      {
        std::string var;
        get_var_name( ((SymSExpr*)code)->s, var );
        indent( os, ind );
        os << retModString.c_str() << "e_" << var.c_str() << ";" << std::endl;
        add_global_sym( var ); 
      }
      indent( os, ind );
      os << incString.c_str() << std::endl;
    }
    break;
  default:
    switch( code->getop() )
    {
    case APP:
      {
        //collect the arguments
        std::vector< Expr* > argVector;
        code->collect_args( argVector );
        //write the arguments
        std::vector< std::string > args;
        for( int a=0; a<(int)argVector.size(); a++ )
        {
          std::string expr;
          write_expr( argVector[a], os, ind, expr );
          args.push_back( expr );
        }
        //write_args( (CExpr*)code, os, ind, 1, args );
        Expr* hd = code->get_head();
        //map to a program in the case that it is a program
        if( hd->getop()==PROG && get_prog_index_by_expr( hd )!=-1 )
        {
          indent( os, ind );
          os << retModString << "f_" << progNames[ get_prog_index_by_expr( hd ) ].c_str() << "( ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << " );" << std::endl;
          for( int a=0; a<(int)args.size(); a++ )
          {
            write_dec( args[a], os, ind );
          }
        }
        else
        {
#ifdef USE_FLAT_APP
          std::string expr;
          write_expr( hd, os, ind, expr );
          indent( os, ind );
          os << retModString << "new CExpr( APP, ";
          os << expr.c_str() << ", ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << " );" << std::endl;
#else
          std::string expr;
          write_expr( hd, os, ind, expr );
          indent( os, ind );
          os << retModString;
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << "new CExpr( APP, ";
          }
          os << expr.c_str() << ", ";
          for( int a=0; a<(int)args.size(); a++ )
          {
            os << args[a].c_str();
            os << " )";
            if( a!=(int)( args.size()-1 ) ){
              os << ", ";
            }
          }
          os << ";" << std::endl;
#endif
          //indent( os, ind );
          //os << expr.c_str() << "->dec();" << std::endl;
        }
      }
      break;
    case MATCH:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr );
        //get the head
        std::ostringstream sshd;
        sshd << "e" << exprCount;
        exprCount++;
        indent( os, ind );
        os << "Expr* " << sshd.str().c_str() << " = " << expr.c_str() << "->followDefs()->get_head();" << std::endl;
        //write the arguments
        std::vector< std::string > args;
        write_args( (CExpr*)code, os, ind, 1, args );
        bool encounterDefault = false;
        //now make an if statement corresponding to the match 
        int a = 0;
        while( ((CExpr*)code)->kids[a+1] )
        {
          indent( os, ind );
          if( a!=0 ){
            os << "}else";
          }
          if( ((CExpr*)code)->kids[a+1]->getop()!=CASE ){
            encounterDefault = true;
            os << "{" << std::endl;
            //write the body of the case
            write_code( ((CExpr*)code)->kids[a+1], os, ind+1, retModStr ); 
            indent( os, ind );
            os << "}" << std::endl;
          }else{
            if( a!=0 )
              os << " ";
            os << "if( " << sshd.str().c_str() << "==" << args[a].c_str() << " ){" << std::endl;
            //collect args from the variable in the code
            std::ostringstream ssargs;
            ssargs << "args" << argsCount;
            argsCount++;
#ifndef USE_FLAT_APP
            indent( os, ind+1 );
            os << "std::vector< Expr* > " << ssargs.str().c_str() << ";" << std::endl;
            indent( os, ind+1 );
            os << expr.c_str() << "->followDefs()->collect_args( " << ssargs.str().c_str() << " );" << std::endl;
#endif
            //set the variables defined in the pattern equal to the arguments
            std::vector< Expr* > caseArgs;
            ((CExpr*)((CExpr*)code)->kids[a+1])->kids[0]->collect_args( caseArgs );
            for( int b=0; b<(int)caseArgs.size(); b++ )
            {
              indent( os, ind+1 );
              os << "Expr* ";
              write_variable( ((SymSExpr*)caseArgs[b])->s.c_str(), os );
#ifdef USE_FLAT_APP
              os << " = ((CExpr*)" << expr.c_str() << "->followDefs())->kids[" << b+1 << "];" << std::endl;
#else
              os << " = " << ssargs.str().c_str() << "[" << b << "];" << std::endl;
#endif
              vars.push_back( ((SymSExpr*)caseArgs[b])->s );
            }
            //write the body of the case
            write_code( ((CExpr*)code)->kids[a+1], os, ind+1, retModStr, opt_write_case_body ); 
          }
          a++;
        }
        if( !encounterDefault )
        {
          indent( os, ind );
          os << "}else{" << std::endl;
          indent( os, ind + 1 );
          os << "std::cout << \"Could not find match for expression in function f_";
          os << progNames[currProgram].c_str() << " \";" << std::endl;
          indent( os, ind + 1 );
          os << sshd.str().c_str() << "->print( std::cout );" << std::endl;
          indent( os, ind + 1 );
          os << "std::cout << std::endl;" << std::endl;
          indent( os, ind + 1 );
          os << "exit( 1 );" << std::endl;
          indent( os, ind );
          os << "}" << std::endl;
        }
        write_dec( expr, os, ind );
        for( int a=0; a<(int)args.size(); a++ )
        {
          write_dec( args[a], os, ind );
        }
      }
      break;
    case CASE:
      if( opts&opt_write_case_body )
      {
        write_code( ((CExpr*)code)->kids[1], os, ind, retModStr );
      }
      else
      {
        write_code( ((CExpr*)code)->kids[0]->get_head(), os, ind, retModStr );
      }
      break;
    case DO:
      {
        //write each of the children in sequence
        int counter = 0;
        while( ((CExpr*)code)->kids[counter] )
        {
          if( ((CExpr*)code)->kids[counter+1]==NULL )
          {
            write_code( ((CExpr*)code)->kids[counter], os, ind, retModStr );
          }
          else
          {
            std::string expr;
            write_expr( ((CExpr*)code)->kids[counter], os, ind, expr );
            //clean up memory
            write_dec( expr, os, ind );
          }
          counter++;
        }
      }
      break;
    case LET:
      {
        indent( os, ind );
        os << "Expr* ";
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, os );
        os << ";" << std::endl;
        std::ostringstream ss;
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, ss );
        write_code( ((CExpr*)code)->kids[1], os, ind, ss.str().c_str() );
        //add it to the variables
        vars.push_back( ((SymSExpr*)((CExpr*)code)->kids[0])->s );
        write_code( ((CExpr*)code)->kids[2], os, ind, retModStr );
        //clean up memory
        indent( os, ind );
        write_variable( ((SymSExpr*)((CExpr*)code)->kids[0])->s, os );
        os << "->dec();" << std::endl;
      }
      break;
    case FAIL:
      {
        indent( os, ind );
        os << retModString.c_str() << "NULL;" << std::endl;
      }
      break;
#ifndef MARKVAR_32
    case MARKVAR:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr, opt_write_check_sym_expr );
        //set the mark on the expression
        indent( os, ind );
        os << "if (" << expr.c_str() << "->followDefs()->getmark())" << std::endl;
        indent( os, ind+1 );
        os << expr.c_str() << "->followDefs()->clearmark();" << std::endl;
        indent( os, ind );
        os << "else" << std::endl;
        indent( os, ind+1 );
        os << expr.c_str() << "->followDefs()->setmark();" << std::endl;
        //write the return if necessary
        if( retModStr!=NULL ){
          indent( os, ind );
          os << retModString.c_str() << expr.c_str() << ";" << std::endl;
          indent( os, ind );
          os << incString.c_str() << std::endl;
        }
        write_dec( expr, os, ind );
      }
      break;
    case IFMARKED:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr, opt_write_check_sym_expr );
        //if mark is set, write code for kids[1]
        indent( os, ind );
        os << "if (" << expr.c_str() << "->followDefs()->getmark()){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+1, retModStr );
        //else write code for kids[2]
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr, os, ind );
      }
      break;
#else
    case MARKVAR:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr, opt_write_check_sym_expr );
        //set the mark on the expression
        indent( os, ind );
        os << "if ( ((SymExpr*)" << expr.c_str() << "->followDefs())->getmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << "))" << std::endl;
        indent( os, ind+1 );
        os << "((SymExpr*)" << expr.c_str() << "->followDefs())->clearmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ");" << std::endl;
        indent( os, ind );
        os << "else" << std::endl;
        indent( os, ind+1 );
        os << "((SymExpr*)" << expr.c_str() << "->followDefs())->setmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ");" << std::endl;
        //write the return if necessary
        if( retModStr!=NULL ){
          indent( os, ind );
          os << retModString.c_str() << expr.c_str() << ";" << std::endl;
          indent( os, ind );
          os << incString.c_str() << std::endl;
        }
        write_dec( expr, os, ind );
      }
      break;
    case COMPARE:
      {
        std::string expr1, expr2;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1, opt_write_check_sym_expr );
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr2, opt_write_check_sym_expr );
        indent( os, ind );
        os << "if( ((SymExpr*)" << expr1.c_str() << ")->followDefs() < ((SymExpr*)" << expr2.c_str() << ")->followDefs() ){" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[3], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
        write_dec( expr2, os, ind );
      }
      break;
    case IFMARKED:
      {
        //calculate the value for the expression
        std::string expr;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr, opt_write_check_sym_expr );
        //if mark is set, write code for kids[1]
        indent( os, ind );
        os << "if ( ((SymExpr*)" << expr.c_str() << "->followDefs())->getmark(";
        os << ((IntExpr*)((CExpr*)code)->kids[0])->get_num() << ")){" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+1, retModStr );
        //else write code for kids[2]
        indent( os, ind );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[3], os, ind+1, retModStr );
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr, os, ind );
      }
      break;
#endif
    case ADD:
    case MUL:
    case DIV:
      {
        //calculate the value for the first expression
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        //calculate the value for the second expression
        std::string expr2;
        write_expr( ((CExpr*)code)->kids[1], os, ind, expr2 );
        std::ostringstream ss;
        ss << "rnum" << rnumCount;
        rnumCount++;
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpz_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpz_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpz_";
        if( code->getop()==ADD )
          os << "add";
        else
          os << "mul";
        os << "( " << ss.str().c_str() << ", ((IntExpr*)" << expr1.c_str() << "->followDefs())->n, ((IntExpr*)" << expr2.c_str() << "->followDefs())->n);" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new IntExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpq_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpq_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpq_";
        if( code->getop()==ADD )
          os << "add";
        else if( code->getop()==MUL )
          os << "mul";
        else
          os << "div";
        os << "( " << ss.str().c_str() << ", ((RatExpr*)" << expr1.c_str() << "->followDefs())->n, ((RatExpr*)" << expr2.c_str() << "->followDefs())->n);" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new RatExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
        write_dec( expr2, os, ind );
      }
      break;
    case NEG:
      {
        //calculate the value for the first expression
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        std::ostringstream ss;
        ss << "rnum" << rnumCount;
        rnumCount++;
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpz_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpz_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpz_neg( " << ss.str().c_str() << ", ((IntExpr*)" << expr1.c_str() << "->followDefs())->n );" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new IntExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "mpq_t " << ss.str().c_str() << ";" << std::endl;
        indent( os, ind+1 );
        os << "mpq_init(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind+1 );
        os << "mpq_neg( " << ss.str().c_str() << ", ((RatExpr*)" << expr1.c_str() << "->followDefs())->n );" << std::endl;
        indent( os, ind+1 );
        os << retModString.c_str() << "new RatExpr(" << ss.str().c_str() << ");" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
      }
      break;
    case IFNEG:
    case IFZERO:
      {
        std::string expr1;
        write_expr( ((CExpr*)code)->kids[0], os, ind, expr1 );
        indent( os, ind );
        os << "if( " << expr1.c_str() << "->followDefs()->getclass()==INT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "if( mpz_sgn( ((IntExpr *)" << expr1.c_str() << "->followDefs())->n ) ";
        if( code->getop()==IFNEG )
          os << "<";
        else
          os << "==";
        os << " 0 ){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}" << std::endl;
        indent( os, ind );
        os << "}else if( " << expr1.c_str() << "->followDefs()->getclass()==RAT_EXPR ){" << std::endl;
        indent( os, ind+1 );
        os << "if( mpq_sgn( ((RatExpr *)" << expr1.c_str() << "->followDefs())->n ) ";
        if( code->getop()==IFNEG )
          os << "<";
        else
          os << "==";
        os << " 0 ){" << std::endl;
        write_code( ((CExpr*)code)->kids[1], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}else{" << std::endl;
        write_code( ((CExpr*)code)->kids[2], os, ind+2, retModStr );
        indent( os, ind+1 );
        os << "}" << std::endl;
        indent( os, ind );
        os << "}" << std::endl;
        //clean up memory
        write_dec( expr1, os, ind );
      }
      break;
    case RUN:/*?*/break;
    case PI:/*?*/break;
    case LAM:/*?*/break;
    case TYPE:/*?*/break;
    case KIND:/*?*/break;
    case ASCRIBE:/*?*/break;
    case MPZ:/*?*/break;
    case PROG:/*?*/break;
    case PROGVARS:/*?*/break;
    case PAT:/*?*/break;
    }
    break;
  }
}
Пример #7
0
ECCVA::ECCVA() {
	mpz_init(p);
	mpz_init(n);
	mpz_init(m);
}
Пример #8
0
 /** Default constructor */
 Event(): _type(0), _dTime(0.0), _k(0), _reschedule(false)
 {
   mpz_init(_timeOfEvent);
   mpz_init(_tickIncrement);
 };
Пример #9
0
 void init(ElementType& result) const { mpz_init(&result); }
//MAIN LOGIC BEGINS
int main() {

  //first unsigned int=total length of the actual representation, char = first 8 digits of the actual representation,
  //each KeyObject has these properties:
  //unsigned int unencodedLength; the total length of the unencoded number
  //unsigned int firstNDigits; the first 32 digits of the unencoded number
  //unsigned int primeRepresentation; the encoded representation of the number/key
  std::vector<KeyObject> keys;
  for(unsigned int i=0; i < 10000; i++){
      keys.push_back(KeyObject());
  }

  //unsigned int initialLowerBoundIndex = 0;
  //recursiveFillKeys(lowerBounds,upperBounds,initialLowerBoundIndex,keys,primes);

  //simple examle of generating the keys structure. (these are the numbers we will reduce the file to,
  //we store them in our ultra compact representation with some identifying info)
  //for (unsigned int i=6; i<10; i++){
  //  for (unsigned int j=6; j<10; j++){
  //    keys[(h-6)*16 + (i-6)*4 + (j-6)] = unsigned integerExponent(prime[0],i)*unsigned integerExponent(prime[1],j)....
  //  }
  //}

  Vvi input(build_input());
  std::cout << input << "\n";

  Vvi output;
  cart_product(input, output);
  std::cout << output << "\n";

  //sample input/output
  //input
  //  (
  //   (0, 1, 2, )
  //   (10, 11, 12, )
  //   (20, 21, 22, )
  //   )
  //  output
  //  (
  //   (0, 10, 20, )
  //   (1, 10, 20, )
  //   (2, 10, 20, )
  //   (0, 11, 20, )
  //   (1, 11, 20, )
  //   (2, 11, 20, )
  //   (0, 12, 20, )
  //   (1, 12, 20, )
  //   (2, 12, 20, )
  //   (0, 10, 21, )
  //   (1, 10, 21, )
  //   (2, 10, 21, )
  //   (0, 11, 21, )
  //   (1, 11, 21, )
  //   (2, 11, 21, )
  //   (0, 12, 21, )
  //   (1, 12, 21, )
  //   (2, 12, 21, )
  //   (0, 10, 22, )
  //   (1, 10, 22, )
  //   (2, 10, 22, )
  //   (0, 11, 22, )
  //   (1, 11, 22, )
  //   (2, 11, 22, )
  //   (0, 12, 22, )
  //   (1, 12, 22, )
  //   (2, 12, 22, ))
  unsigned int counter = 0;
  for(Vvi::iterator it = output.begin(); ; ) {
    //keyExponentValues gives us a vector with all the exponents we need to use
    //to create a key
    //here we calculate the number represented by the exponents

    mpz_t n;
    mpz_init(n);
    mpz_set(n,1);
    for (Vi::iterator keyExponentValues = it->begin(); ; ){
      mpz_t k;
      mpz_init(k);
      mpz_set(k,globals.primes[counter]);
      mpz_mul(n,n,k);
      n *= k;
      mpz_clear (k);
      //mpz_sizeinbase (mpz_t op, int base)
      //mpz_sizeinbase (mpz_t op, int base)
      //base can only be up to size 62 max!
      //here we store the length of the number represented by the exponents
      keys[counter].unencodedLength = 0;

      //here we store the first n digits of the number represented by the exponents
      keys[counter].firstNDigits = 0;
      mpz_clear (n);

      //this simulates log base 2
      unsigned int bitsToStoreExponent= 0;
      unsigned int exponentRange = globals.exponentMax - globals.exponentMin;
      while (exponentRange >>= 1) ++bitsToStoreExponent;
      //IMPORTANT ENCODING LOCATED RIGHT HERE IN THIS COMMENT!!!
      //00 = 6th power, 01=7th, 10=8th, 11=9th,
      //first 2 bits are for 2, next 2 are for 3, next 2 are for 5, etc. etc.
      unsigned int exponentCounter = 0;
      for(Vi::iterator keyExponentValues = it->begin(); ; ) {
        for (int j=globals.exponentMin; j<globals.exponentMax; j++){
          for (int k=0;k<bitsToStoreExponent;k++){
            //set i'th prime number bits to appropiate value between 0 and 2^k for exponent value j
            //globals.exponentMin - j want to turn this into binary representation, get appropriate number for ith place
            if (k==j){
              //keys[counter].primeRepresentation();
              //(globals.exponentMin - j) might be useful
              if (*keyExponentValues % intPow(2,k)==0){//base 10 number convert to base two, get ith digit.
                keys[counter].primeRepresentation.set(globals.howManyOfFirstNBitsStoredInKey
                                                      - exponentCounter*bitsToStoreExponent,1);
              }
              else{
                keys[counter].primeRepresentation.set(globals.howManyOfFirstNBitsStoredInKey
                                                      - exponentCounter*bitsToStoreExponent,0);
              }
            }
          }
        }
        //illustrative but less general example
        //switch(keyExponentValues->me[i]){
        //  case 6:
        //    keys[counter].primeRepresentation();
        //    keys[counter].primeRepresentation.set[32-i*2,0];
        //    keys[counter].primeRepresentation.set[31-i*2,0];
        //    break;
        //  case 7:
        //    keys[counter].primeRepresentation();
        //    keys[counter].primeRepresentation.set[32,0];
        //    keys[counter].primeRepresentation.set[31,1];
        //    break;
        //  case 8:
        //    keys[counter].primeRepresentation();
        //    keys[counter].primeRepresentation.set[32,1];
        //    keys[counter].primeRepresentation.set[31,0];
        //    break;
        //  case 9:
        //    keys[counter].primeRepresentation();
        //    keys[counter].primeRepresentation.set[32,1];
        //    keys[counter].primeRepresentation.set[31,1];
        //    break;
        //}
        exponentCounter++;
        keyExponentValues++;
      }
    }
    counter++;
    it++;
  }



  //HERE IS WHERE WE READ THE FILE IN THAT WE WILL ENCODE
  //TODO move this to a different section
  //char* input = getInputFromFile();

  //unsigned int i = 0;
  //while (input[i] != '\0'){
  //}
  return 0;
}
Пример #11
0
int main(int argc, char **argv) {
  int err, option_index, c, clientlen, counter;
  unsigned char rcv_plaintext[AES_BLOCK_SIZE];
  unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
  unsigned char send_plaintext[AES_BLOCK_SIZE];
  unsigned char send_ciphertext[AES_BLOCK_SIZE];
  aes_context enc_ctx, dec_ctx;
  in_addr_t ip_addr;
  struct sockaddr_in server_addr;
  FILE *c_file, *d_file, *m_file;
  ssize_t read_size, write_size;
  struct sockaddr_in client_addr;
  tls_msg err_msg, send_msg, rcv_msg;
  mpz_t client_exp, client_mod; 
  fd_set readfds;
  struct timeval tv;

  c_file = d_file = m_file = NULL;

  mpz_init(client_exp);
  mpz_init(client_mod);

  /*
   * This section is networking code that you don't need to worry about.
   * Look further down in the function for your part.
   */

  memset(&ip_addr, 0, sizeof(in_addr_t));

  option_index = 0;
  err = 0;

  static struct option long_options[] = {
    {"ip", required_argument, 0, 'i'},
    {"cert", required_argument, 0, 'c'},
    {"exponent", required_argument, 0, 'd'},
    {"modulus", required_argument, 0, 'm'},
    {0, 0, 0, 0},
  };

  while (1) {
    c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
    if (c < 0) {
      break;
    }
    switch(c) {
    case 0:
      usage();
      break;
    case 'c':
      c_file = fopen(optarg, "r");
      if (c_file == NULL) {
	perror("Certificate file error");
	exit(1);
      }
      break;
    case 'd':
      d_file = fopen(optarg, "r");
      if (d_file == NULL) {
	perror("Exponent file error");
	exit(1);
      }
      break;
    case 'i':
      ip_addr = inet_addr(optarg);
      break;
    case 'm':
      m_file = fopen(optarg, "r");
      if (m_file == NULL) {
	perror("Modulus file error");
	exit(1);
      }
      break;
    case '?':
      usage();
      break;
    default:
      usage();
      break;
    }
  }

  if (d_file == NULL || c_file == NULL || m_file == NULL) {
    usage();
  }
  if (argc != 9) {
    usage();
  }

  mpz_inp_str(client_exp, d_file, 0);
  mpz_inp_str(client_mod, m_file, 0);

  signal(SIGTERM, kill_handler);

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    perror("Could not open socket");
    exit(1);
  }

  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = ip_addr;
  server_addr.sin_port = htons(HANDSHAKE_PORT);
  err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
  if (err < 0) {
    perror("Could not bind socket");
    cleanup();
  }

  // YOUR CODE HERE

  // IMPLEMENT THE TLS HANDSHAKE
  // Client Hello and Setup
  hello_message client_hello_send[HELLO_MSG_SIZE];
  (*client_hello_send).type = CLIENT_HELLO;
  (*client_hello_send).random = random_int();
  (*client_hello_send).cipher_suite = TLS_RSA_WITH_AES_128_ECB_SHA256;
  send_tls_message(sockfd, client_hello_send, HELLO_MSG_SIZE);
 
  // Server Hello & Setup
  hello_message server_hello_rcv[HELLO_MSG_SIZE];
  receive_tls_message(sockfd, server_hello_rcv, HELLO_MSG_SIZE, SERVER_HELLO);
    
  // Client Certificate
  cert_message client_cert_send[CERT_MSG_SIZE];
  (*client_cert_send).type = CLIENT_CERTIFICATE;
  fread((*client_cert_send).cert, RSA_MAX_LEN, 1, c_file);

  //Printing the client certificate message
  //printf("%s\n",(*client_cert_send).cert);
  send_tls_message(sockfd, client_cert_send, CERT_MSG_SIZE);

  // Server Certificate
  cert_message server_cert_rcv[CERT_MSG_SIZE];
  receive_tls_message(sockfd, server_cert_rcv, CERT_MSG_SIZE, SERVER_CERTIFICATE);

  mpz_t decrypted_cert;
  mpz_t ca_exp;
  mpz_t ca_mod;
  mpz_init(decrypted_cert);
  mpz_init(ca_exp);
  mpz_init(ca_mod);

  mpz_set_str(ca_exp, CA_EXPONENT, 0);
  mpz_set_str(ca_mod, CA_MODULUS, 0);

  // Decrypt Server Certificate
  decrypt_cert(decrypted_cert, server_cert_rcv, ca_exp, ca_mod); 
  char output_str[CERT_MSG_SIZE];
  mpz_get_ascii(output_str, decrypted_cert);

  // Extracting keys from certificate 
  mpz_t public_exp;
  mpz_t public_mod;
  mpz_init(public_exp);
  mpz_init(public_mod);
  get_cert_exponent(public_exp, output_str);
  get_cert_modulus(public_mod, output_str);
<<<<<<< HEAD
Пример #12
0
/* s <- 1 + r/1! + r^2/2! + ... + r^l/l! while MPFR_EXP(r^l/l!)+MPFR_EXPR(r)>-q
   using Brent/Kung method with O(sqrt(l)) multiplications.
   Return l.
   Uses m multiplications of full size and 2l/m of decreasing size, 
   i.e. a total equivalent to about m+l/m full multiplications,
   i.e. 2*sqrt(l) for m=sqrt(l).
   Version using mpz. ss must have at least (sizer+1) limbs.
   The error is bounded by (l^2+4*l) ulps where l is the return value.
*/
static int
mpfr_exp2_aux2 (mpz_t s, mpfr_srcptr r, int q, int *exps)
{
  int expr, l, m, i, sizer, *expR, expt, ql;
  unsigned long int c;
  mpz_t t, *R, rr, tmp;
  TMP_DECL(marker);

  /* estimate value of l */
  l = q / (-MPFR_EXP(r));
  m = (int) _mpfr_isqrt (l);
  /* we access R[2], thus we need m >= 2 */
  if (m < 2) m = 2;
  TMP_MARK(marker);
  R = (mpz_t*) TMP_ALLOC((m+1)*sizeof(mpz_t)); /* R[i] stands for r^i */
  expR = (int*) TMP_ALLOC((m+1)*sizeof(int)); /* exponent for R[i] */
  sizer = 1 + (MPFR_PREC(r)-1)/BITS_PER_MP_LIMB;
  mpz_init(tmp);
  MY_INIT_MPZ(rr, sizer+2);
  MY_INIT_MPZ(t, 2*sizer); /* double size for products */
  mpz_set_ui(s, 0); *exps = 1-q; /* initialize s to zero, 1 ulp = 2^(1-q) */
  for (i=0;i<=m;i++) MY_INIT_MPZ(R[i], sizer+2);
  expR[1] = mpfr_get_z_exp(R[1], r); /* exact operation: no error */
  expR[1] = mpz_normalize2(R[1], R[1], expR[1], 1-q); /* error <= 1 ulp */
  mpz_mul(t, R[1], R[1]); /* err(t) <= 2 ulps */
  mpz_div_2exp(R[2], t, q-1); /* err(R[2]) <= 3 ulps */
  expR[2] = 1-q;
  for (i=3;i<=m;i++) {
    mpz_mul(t, R[i-1], R[1]); /* err(t) <= 2*i-2 */
    mpz_div_2exp(R[i], t, q-1); /* err(R[i]) <= 2*i-1 ulps */
    expR[i] = 1-q;
  }
  mpz_set_ui(R[0], 1); mpz_mul_2exp(R[0], R[0], q-1); expR[0]=1-q; /* R[0]=1 */
  mpz_set_ui(rr, 1); expr=0; /* rr contains r^l/l! */
  /* by induction: err(rr) <= 2*l ulps */

  l = 0;
  ql = q; /* precision used for current giant step */
  do {
    /* all R[i] must have exponent 1-ql */
    if (l) for (i=0;i<m;i++) {
      expR[i] = mpz_normalize2(R[i], R[i], expR[i], 1-ql);
    }
    /* the absolute error on R[i]*rr is still 2*i-1 ulps */
    expt = mpz_normalize2(t, R[m-1], expR[m-1], 1-ql); 
    /* err(t) <= 2*m-1 ulps */
    /* computes t = 1 + r/(l+1) + ... + r^(m-1)*l!/(l+m-1)! 
       using Horner's scheme */
    for (i=m-2;i>=0;i--) {
      mpz_div_ui(t, t, l+i+1); /* err(t) += 1 ulp */
      mpz_add(t, t, R[i]);
    }
    /* now err(t) <= (3m-2) ulps */
    
    /* now multiplies t by r^l/l! and adds to s */
    mpz_mul(t, t, rr); expt += expr;
    expt = mpz_normalize2(t, t, expt, *exps);
    /* err(t) <= (3m-1) + err_rr(l) <= (3m-2) + 2*l */
#ifdef DEBUG
    if (expt != *exps) {
      fprintf(stderr, "Error: expt != exps %d %d\n", expt, *exps); exit(1);
    }
#endif
    mpz_add(s, s, t); /* no error here */

    /* updates rr, the multiplication of the factors l+i could be done 
       using binary splitting too, but it is not sure it would save much */
    mpz_mul(t, rr, R[m]); /* err(t) <= err(rr) + 2m-1 */
    expr += expR[m];
    mpz_set_ui (tmp, 1);
    for (i=1, c=1; i<=m; i++) {
      if (l+i > ~((unsigned long int) 0)/c) {
	mpz_mul_ui(tmp, tmp, c);
	c = l+i;
      }
      else c *= (unsigned long int) l+i;
    }
    if (c != 1) mpz_mul_ui (tmp, tmp, c); /* tmp is exact */
    mpz_fdiv_q(t, t, tmp); /* err(t) <= err(rr) + 2m */
    expr += mpz_normalize(rr, t, ql); /* err_rr(l+1) <= err_rr(l) + 2m+1 */
    ql = q - *exps - mpz_sizeinbase(s, 2) + expr + mpz_sizeinbase(rr, 2);
    l+=m;
  } while (expr+mpz_sizeinbase(rr, 2) > -q);

  TMP_FREE(marker);
  mpz_clear(tmp);
  return l;
}
Пример #13
0
void mpfr_stats (unsigned long num, mpfr_prec_t prec_a, mpfr_prec_t prec_b, 
		 mpfr_prec_t prec_c, unsigned long seed)
{
  mpf_t xt[num],yt[num],zt[num];
  unsigned long long mc[num][MAX_OP], m;
  mpfr_t a, b, c;
  mpf_t x, y, z;
  mpz_t zz;
  unsigned long long min,max,moy;
  gmp_randstate_t state;
  int i,j=0, op, cont;
  int imin=0, imax=0;

  mpf_init2(x, prec_a);
  mpf_init2(y, prec_b);
  mpf_init2(z, prec_c);

  mpfr_init2(a, prec_a);
  mpfr_init2(b, prec_b);
  mpfr_init2(c, prec_c);

  gmp_randinit_lc_2exp_size (state, 128);
  gmp_randseed_ui (state, seed);

  mpz_init (zz);
  mpz_urandomb (zz, state, 2*prec_b);

  TIMP_OVERHEAD ();

  for(i = 0 ; i < num ; i++)
    {
      mpf_init2(xt[i],  prec_a);
      mpf_init2(yt[i],  prec_b);
      mpf_init2(zt[i],  prec_c);
      mpf_urandomb(yt[i], state, prec_b); 
      yt[i][0]._mp_exp += (rand() % prec_b) / GMP_NUMB_BITS;
      mpf_urandomb(zt[i], state, prec_c);
      /* zt[i][0]._mp_exp += (rand() % prec_c) / GMP_NUMB_BITS; */
      for(op = 0 ; op < MAX_OP ; op++)
	mc[i][op] = 0xFFFFFFFFFFFFFFFLL;
    }

  for(j = 0, cont = 5 ; cont ; j++, cont--)
    {
      printf("Pass %d...\n", j+1);
      for(i = 0 ; i < num ; i++)
	{
	  op = 0;
	  mpf_set(y,yt[i]);
	  mpf_set(z,zt[i]);
	  mpfr_set_f(b, yt[i], GMP_RNDN);
	  mpfr_set_f(c, zt[i], GMP_RNDN);
#undef BENCH
#define BENCH(TEST_STR, TEST)                                           \
 m = TIMP_MEASURE(TEST); if (m < mc[i][op]) {mc[i][op] = m; cont = 4;} op++;
	  TEST_LIST;
	}

#undef BENCH
#define BENCH(TEST_STR, TEST)                                       \
  min = 0xFFFFFFFFFFFFFFFLL; max = 0LL; moy = 0LL;                  \
  for(i = 0 ; i < num ; i++) {                                      \
      if (mc[i][op] < min) imin = i, min = mc[i][op];               \
      if (mc[i][op] > max) imax = i, max = mc[i][op];               \
      moy += mc[i][op];                                             \
    }                                                               \
  printf(" %s: %Lu / %Lu.%02Lu / %Lu", TEST_STR, min,               \
	 (unsigned long long) moy/num, (moy*100LL/num)%100LL, max); \
  if (verbose) printf ("\tMIN:%e,%e\tMAX:%e,%e", mpf_get_d(yt[imin]),\
		       mpf_get_d(zt[imin]), mpf_get_d(yt[imax]),    \
		       mpf_get_d(zt[imax]));                        \
  putchar ('\n');                                                   \
  op++;

      op =0;
      TEST_LIST;
     }

  printf("End\n");
  mpz_clear (zz);
  mpfr_clear(a);
  mpfr_clear(b);
  mpfr_clear(c);
  mpf_clear(x);
  mpf_clear(y);
  mpf_clear(z);
  for(i = 0 ; i < num ; i++)
    {
      mpf_clear(xt[i]);
      mpf_clear(yt[i]);
      mpf_clear(zt[i]);
    }
  gmp_randclear(state);
}
Пример #14
0
/*
 * Runs sender operations for Naor-Pinkas semi-honest OT
 */
int
ot_np_send(struct state *st, void *msgs, int maxlength, int num_ots, int N,
           ot_msg_reader ot_msg_reader, ot_item_reader ot_item_reader)
{
    mpz_t r, gr, pk, pk0;
    mpz_t *Cs = NULL, *Crs = NULL, *pk0s = NULL;
    char buf[field_size], *msg = NULL;
    int err = 0;
    double start, end;

#ifdef AES_HW
    fprintf(stderr, "OT-NP: Using AESNI\n");
#endif
#ifdef SHA
    fprintf(stderr, "OT-NP: Using SHA-1\n");
#endif

    start = current_time();

    mpz_inits(r, gr, pk, pk0, NULL);

    msg = (char *) ot_malloc(sizeof(char) * maxlength);
    if (msg == NULL)
        ERROR;
    Cs = (mpz_t *) ot_malloc(sizeof(mpz_t) * (N - 1));
    if (Cs == NULL)
        ERROR;
    Crs = (mpz_t *) ot_malloc(sizeof(mpz_t) * (N - 1));
    if (Crs == NULL)
        ERROR;
    pk0s = (mpz_t *) ot_malloc(sizeof(mpz_t) * num_ots);
    if (pk0s == NULL)
        ERROR;

    for (int i = 0; i < num_ots; ++i) {
        mpz_init(pk0s[i]);
    }

#ifdef AES_HW
    AES_KEY key;
    AES_set_encrypt_key((unsigned char *) "abcd", 128, &key);
#endif

    // choose r \in_R Zq
    random_element(r, &st->p);
    // compute g^r
    mpz_powm(gr, st->p.g, r, st->p.p);

    // choose C_i's \in_R Zq
    for (int i = 0; i < N - 1; ++i) {
        mpz_inits(Cs[i], Crs[i], NULL);
        random_element(Cs[i], &st->p);
    }

    end = current_time();
    fprintf(stderr, "Initialization: %f\n", end - start);

    // send g^r to receiver
    start = current_time();
    mpz_to_array(buf, gr, sizeof buf);
    if (sendall(st->sockfd, buf, sizeof buf) == -1)
        ERROR;
    end = current_time();
    fprintf(stderr, "Send g^r to receiver: %f\n", end - start);

    // send Cs to receiver
    start = current_time();
    for (int i = 0; i < N - 1; ++i) {
        mpz_to_array(buf, Cs[i], sizeof buf);
        if (sendall(st->sockfd, buf, sizeof buf) == -1)
            ERROR;
    }
    end = current_time();
    fprintf(stderr, "Send Cs to receiver: %f\n", end - start);

    start = current_time();
    for (int i = 0; i < N - 1; ++i) {
        // compute C_i^r
        mpz_powm(Crs[i], Cs[i], r, st->p.p);
    }
    end = current_time();
    fprintf(stderr, "Compute C_i^r: %f\n", end - start);

    start = current_time();
    for (int j = 0; j < num_ots; ++j) {
        // get pk0 from receiver
        if (recvall(st->sockfd, buf, sizeof buf) == -1)
            ERROR;
        array_to_mpz(pk0s[j], buf, sizeof buf);
    }
    end = current_time();
    fprintf(stderr, "Get pk0 from receiver: %f\n", end - start);

    for (int j = 0; j < num_ots; ++j) {
        void *ot = ot_msg_reader(msgs, j);
        for (int i = 0; i < N; ++i) {
            char *item;
            ssize_t itemlength;

            if (i == 0) {
                // compute pk0^r
                mpz_powm(pk0, pk0s[j], r, st->p.p);
                mpz_to_array(buf, pk0, sizeof buf);
                (void) mpz_invert(pk0, pk0, st->p.p);
            } else {
                mpz_mul(pk, pk0, Crs[i - 1]);
                mpz_mod(pk, pk, st->p.p);
                mpz_to_array(buf, pk, sizeof buf);
            }

#ifdef AES_HW
            if (AES_encrypt_message((unsigned char *) buf, sizeof buf,
                                    (unsigned char *) msg, maxlength, &key))
                ERROR;
#endif
#ifdef SHA
            (void) memset(msg, '\0', maxlength);
            sha1_hash(msg, maxlength, i, (unsigned char *) buf, sizeof buf);
#endif            

            ot_item_reader(ot, i, &item, &itemlength);
            assert(itemlength <= maxlength);

            xorarray((unsigned char *) msg, maxlength,
                     (unsigned char *) item, itemlength);
            if (sendall(st->sockfd, msg, maxlength) == -1)
                ERROR;
        }
    }

 cleanup:
    mpz_clears(r, gr, pk, pk0, NULL);

    if (pk0s) {
        for (int i = 0; i < num_ots; ++i) {
            mpz_clear(pk0s[i]);
        }
        ot_free(pk0s);
    }
    if (Crs) {
        for (int i = 0; i < N - 1; ++i)
            mpz_clear(Crs[i]);
        ot_free(Crs);
    }
    if (Cs) {
        for (int i = 0; i < N - 1; ++i)
            mpz_clear(Cs[i]);
        ot_free(Cs);
    }
    if (msg)
        ot_free(msg);

    return err;
}
Пример #15
0
Файл: exp3.c Проект: Canar/mpfr
int
mpfr_exp_3 (mpfr_ptr y, mpfr_srcptr x, mpfr_rnd_t rnd_mode)
{
    mpfr_t t, x_copy, tmp;
    mpz_t uk;
    mpfr_exp_t ttt, shift_x;
    unsigned long twopoweri;
    mpz_t *P;
    mpfr_prec_t *mult;
    int i, k, loop;
    int prec_x;
    mpfr_prec_t realprec, Prec;
    int iter;
    int inexact = 0;
    MPFR_SAVE_EXPO_DECL (expo);
    MPFR_ZIV_DECL (ziv_loop);

    MPFR_LOG_FUNC
    (("x[%Pu]=%.*Rg rnd=%d", mpfr_get_prec(x), mpfr_log_prec, x, rnd_mode),
     ("y[%Pu]=%.*Rg inexact=%d", mpfr_get_prec(y), mpfr_log_prec, y,
      inexact));

    MPFR_SAVE_EXPO_MARK (expo);

    /* decompose x */
    /* we first write x = 1.xxxxxxxxxxxxx
       ----- k bits -- */
    prec_x = MPFR_INT_CEIL_LOG2 (MPFR_PREC (x)) - MPFR_LOG2_GMP_NUMB_BITS;
    if (prec_x < 0)
        prec_x = 0;

    ttt = MPFR_GET_EXP (x);
    mpfr_init2 (x_copy, MPFR_PREC(x));
    mpfr_set (x_copy, x, MPFR_RNDD);

    /* we shift to get a number less than 1 */
    if (ttt > 0)
    {
        shift_x = ttt;
        mpfr_div_2ui (x_copy, x, ttt, MPFR_RNDN);
        ttt = MPFR_GET_EXP (x_copy);
    }
    else
        shift_x = 0;
    MPFR_ASSERTD (ttt <= 0);

    /* Init prec and vars */
    realprec = MPFR_PREC (y) + MPFR_INT_CEIL_LOG2 (prec_x + MPFR_PREC (y));
    Prec = realprec + shift + 2 + shift_x;
    mpfr_init2 (t, Prec);
    mpfr_init2 (tmp, Prec);
    mpz_init (uk);

    /* Main loop */
    MPFR_ZIV_INIT (ziv_loop, realprec);
    for (;;)
    {
        int scaled = 0;
        MPFR_BLOCK_DECL (flags);

        k = MPFR_INT_CEIL_LOG2 (Prec) - MPFR_LOG2_GMP_NUMB_BITS;

        /* now we have to extract */
        twopoweri = GMP_NUMB_BITS;

        /* Allocate tables */
        P    = (mpz_t*) (*__gmp_allocate_func) (3*(k+2)*sizeof(mpz_t));
        for (i = 0; i < 3*(k+2); i++)
            mpz_init (P[i]);
        mult = (mpfr_prec_t*) (*__gmp_allocate_func) (2*(k+2)*sizeof(mpfr_prec_t));

        /* Particular case for i==0 */
        mpfr_extract (uk, x_copy, 0);
        MPFR_ASSERTD (mpz_cmp_ui (uk, 0) != 0);
        mpfr_exp_rational (tmp, uk, shift + twopoweri - ttt, k + 1, P, mult);
        for (loop = 0; loop < shift; loop++)
            mpfr_sqr (tmp, tmp, MPFR_RNDD);
        twopoweri *= 2;

        /* General case */
        iter = (k <= prec_x) ? k : prec_x;
        for (i = 1; i <= iter; i++)
        {
            mpfr_extract (uk, x_copy, i);
            if (MPFR_LIKELY (mpz_cmp_ui (uk, 0) != 0))
            {
                mpfr_exp_rational (t, uk, twopoweri - ttt, k  - i + 1, P, mult);
                mpfr_mul (tmp, tmp, t, MPFR_RNDD);
            }
            MPFR_ASSERTN (twopoweri <= LONG_MAX/2);
            twopoweri *=2;
        }

        /* Clear tables */
        for (i = 0; i < 3*(k+2); i++)
            mpz_clear (P[i]);
        (*__gmp_free_func) (P, 3*(k+2)*sizeof(mpz_t));
        (*__gmp_free_func) (mult, 2*(k+2)*sizeof(mpfr_prec_t));

        if (shift_x > 0)
        {
            MPFR_BLOCK (flags, {
                for (loop = 0; loop < shift_x - 1; loop++)
                    mpfr_sqr (tmp, tmp, MPFR_RNDD);
                mpfr_sqr (t, tmp, MPFR_RNDD);
            } );

            if (MPFR_UNLIKELY (MPFR_OVERFLOW (flags)))
            {
                /* tmp <= exact result, so that it is a real overflow. */
                inexact = mpfr_overflow (y, rnd_mode, 1);
                MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, MPFR_FLAGS_OVERFLOW);
                break;
            }

            if (MPFR_UNLIKELY (MPFR_UNDERFLOW (flags)))
            {
                /* This may be a spurious underflow. So, let's scale
                   the result. */
                mpfr_mul_2ui (tmp, tmp, 1, MPFR_RNDD);  /* no overflow, exact */
                mpfr_sqr (t, tmp, MPFR_RNDD);
                if (MPFR_IS_ZERO (t))
                {
                    /* approximate result < 2^(emin - 3), thus
                       exact result < 2^(emin - 2). */
                    inexact = mpfr_underflow (y, (rnd_mode == MPFR_RNDN) ?
                                              MPFR_RNDZ : rnd_mode, 1);
                    MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, MPFR_FLAGS_UNDERFLOW);
                    break;
                }
                scaled = 1;
            }
        }
Пример #16
0
int
main(void)
{
    int i, result;
    FLINT_TEST_INIT(state);

    flint_printf("divexact....");
    fflush(stdout);

    

    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a, b, c;
        mpz_t d, e, f, g;

        fmpz_init(a);
        fmpz_init(b);
        fmpz_init(c);

        mpz_init(d);
        mpz_init(e);
        mpz_init(f);
        mpz_init(g);

        fmpz_randtest(a, state, 200);
        fmpz_randtest_not_zero(b, state, 200);
        fmpz_mul(c, a, b);

        fmpz_get_mpz(d, b);
        fmpz_get_mpz(e, c);

        fmpz_divexact(a, c, b);
        mpz_divexact(f, e, d);

        fmpz_get_mpz(g, a);

        result = (mpz_cmp(f, g) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, e = %Zd, f = %Zd, g = %Zd\n", d, e, f, g);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(b);
        fmpz_clear(c);

        mpz_clear(d);
        mpz_clear(e);
        mpz_clear(f);
        mpz_clear(g);
    }

    /* Check aliasing of a and b */
    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a, c;
        mpz_t d, f, g;

        fmpz_init(a);
        fmpz_init(c);

        mpz_init(d);
        mpz_init(f);
        mpz_init(g);

        fmpz_randtest_not_zero(a, state, 200);

        fmpz_get_mpz(d, a);

        fmpz_divexact(c, a, a);
        mpz_divexact(f, d, d);

        fmpz_get_mpz(g, c);

        result = (mpz_cmp(f, g) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, f = %Zd, g = %Zd\n", d, f, g);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(c);

        mpz_clear(d);
        mpz_clear(f);
        mpz_clear(g);
    }

    /* Test aliasing of a and c */
    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a, b, c;
        mpz_t d, e, f, g;

        fmpz_init(a);
        fmpz_init(b);
        fmpz_init(c);

        mpz_init(d);
        mpz_init(e);
        mpz_init(f);
        mpz_init(g);

        fmpz_randtest(a, state, 200);
        fmpz_randtest_not_zero(b, state, 200);
        fmpz_mul(c, a, b);

        fmpz_get_mpz(d, c);
        fmpz_get_mpz(e, b);

        fmpz_divexact(c, c, b);
        mpz_divexact(f, d, e);

        fmpz_get_mpz(g, c);

        result = (mpz_cmp(f, g) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, e = %Zd, f = %Zd, g = %Zd\n", d, e, f, g);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(b);
        fmpz_clear(c);

        mpz_clear(d);
        mpz_clear(e);
        mpz_clear(f);
        mpz_clear(g);
    }

    /* Test aliasing of b and c */
    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a, b, c;
        mpz_t d, e, f, g;

        fmpz_init(a);
        fmpz_init(b);
        fmpz_init(c);

        mpz_init(d);
        mpz_init(e);
        mpz_init(f);
        mpz_init(g);

        fmpz_randtest(a, state, 200);
        fmpz_randtest_not_zero(b, state, 200);
        fmpz_mul(c, a, b);

        fmpz_get_mpz(d, c);
        fmpz_get_mpz(e, b);

        fmpz_divexact(b, c, b);
        mpz_divexact(f, d, e);

        fmpz_get_mpz(g, b);

        result = (mpz_cmp(f, g) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, e = %Zd, f = %Zd, g = %Zd\n", d, e, f, g);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(b);
        fmpz_clear(c);

        mpz_clear(d);
        mpz_clear(e);
        mpz_clear(f);
        mpz_clear(g);
    }

    FLINT_TEST_CLEANUP(state);
    
    flint_printf("PASS\n");
    return 0;
}
Пример #17
0
int main(void) {
  sollya_obj_t a, prec;
  mpz_t res;
  int i;

  sollya_lib_init();
  mpz_init(res);

  prec = SOLLYA_CONST(20);
  sollya_lib_set_prec_and_print(prec);
  sollya_lib_clear_obj(prec);

  /* something that is obviously not a constant */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("[1;2]");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf("\n\n");
  }
  sollya_lib_clear_obj(a);


  /* something that could be interpreted as constant but that is not a */
  /* constant, strictly speaking */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("[1;1]");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf("\n\n");
  }
  sollya_lib_clear_obj(a);


  /* something that is constant, but it is not obvious */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("3*cos(2*x)/(2*sin(x)*cos(x))");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf("\n\n");
  }
  sollya_lib_clear_obj(a);


  /* An obvious constant */
  mpz_set_ui(res, 17);
  a = SOLLYA_CONST(3);
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting 3)\n\n");
  }
  sollya_lib_clear_obj(a);

  /* A constant, but that does not fit on 20 bits */
  mpz_set_ui(res, 17);
  a = SOLLYA_CONST(1073741824);
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting 1073741824)\n\n");
  }
  sollya_lib_clear_obj(a);

  /* A negative constant */
  mpz_set_ui(res, 17);
  a = SOLLYA_CONST(-3);
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting -3)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant that does not fit in a integer */
  mpz_set_ui(res, 17);
  a = SOLLYA_CONST(1);
  for (i=1;i<=90;i++) a = SOLLYA_MUL(a, SOLLYA_CONST(2));
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expected 1237940039285380274899124224)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* The same, but negative */
  mpz_set_ui(res, 17);
  a = SOLLYA_CONST(-1);
  for (i=1;i<=90;i++) a = SOLLYA_MUL(a, SOLLYA_CONST(2));
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expected -1237940039285380274899124224)\n\n");
  }
  sollya_lib_clear_obj(a);



  /* A constant expression exactly representable as an int but it cannot be decided. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("(1b200+1)-1b200*(log2(3)/log2(7) - log(3)/log(7) + 1)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting 1)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant expression very close to the middle between two integers
   and it cannot be decided. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 + 1b-400 + 0.5*(log2(3)/log2(7) - log(3)/log(7) + 1)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 1 or 2 -- 2 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant expression very close to the middle between two doubles */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 + 1b-400 + 0.5");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 1 or 2 -- 2 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant expression exactly at the middle between two doubles, but
     it cannot be decided. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 - 0.5*(log2(3)/log2(7) - log(3)/log(7) + 1)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 0 or 1 -- 0 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* The same constant but decidable */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 - 0.5");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 0 or 1 -- 0 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* Another constant expression exactly at the middle between two doubles, but
     it cannot be decided. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 + 1.5*(log2(3)/log2(7) - log(3)/log(7) + 1)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 2 or 3 -- 2 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* The same constant but decidable. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("1 + 1.5");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 2 or 3 -- 2 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A transcendantal constant. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("exp(pi) + log(2)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting either 23 or 24 -- 24 would be better)\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant hard to evaluate because exactly zero but undecidable. */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("log10(2)/log10(3) - log(2)/log(3)");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting 0).\n\n");
  }
  sollya_lib_clear_obj(a);


  /* A constant very hard to evaluate (cf. tevaluate_function_at_constant_expression). */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("(sin((pi) / 3) - sqrt(3) / 2) * (1 * 2^(100000)) + 3");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to some number. Expecting that the above warning message states that faithtul evaluation is *NOT* possible.\n\n", a);
  }
  sollya_lib_clear_obj(a);



  /* Trying -inf */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("[email protected]@");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expected 0)\n\n");
  }
  sollya_lib_clear_obj(a);


/* Trying NaN */
  mpz_set_ui(res, 17);
  a = sollya_lib_parse_string("@[email protected]");
  if (!sollya_lib_get_constant_as_mpz(res, a))
    sollya_lib_printf("%b is not a constant.\n\n", a);
  else {
    sollya_lib_printf("%b has been converted to ", a); gmp_printf("%Zd", res); sollya_lib_printf(" (expecting 0).\n\n");
  }
  sollya_lib_clear_obj(a);


  mpz_clear(res);
  sollya_lib_close();
  return 0;
}
Пример #18
0
// Computes a curve and sets fp to the field it is defined over using the
// complex multiplication method, where cm holds the appropriate information
// (e.g. discriminant, field order).
static void compute_cm_curve(d_param_ptr param, pbc_cm_ptr cm) {
  element_t hp, root;
  field_t fp, fpx;
  field_t cc;

  field_init_fp(fp, cm->q);
  field_init_poly(fpx, fp);
  element_init(hp, fpx);

  mpz_t *coefflist;
  int n = (int)pbc_hilbert(&coefflist, cm->D);

  // Temporarily set the coefficient of x^{n-1} to 1 so hp has degree n - 1,
  // allowing us to use poly_coeff().
  poly_set_coeff1(hp, n - 1);
  int i;
  for (i = 0; i < n; i++) {
    element_set_mpz(element_item(hp, i), coefflist[i]);
  }
  pbc_hilbert_free(coefflist, n);

  // TODO: Remove x = 0, 1728 roots.
  // TODO: What if there are no roots?
  //printf("hp ");
  //element_out_str(stdout, 0, hp);
  //printf("\n");

  element_init(root, fp);
  poly_findroot(root, hp);
  //printf("root = ");
  //element_out_str(stdout, 0, root);
  //printf("\n");
  element_clear(hp);
  field_clear(fpx);

  // The root is the j-invariant of the desired curve.
  field_init_curve_j(cc, root, cm->n, NULL);
  element_clear(root);

  // We may need to twist it.
  {
    // Pick a random point P and twist the curve if it has the wrong order.
    element_t P;
    element_init(P, cc);
    element_random(P);
    element_mul_mpz(P, P, cm->n);
    if (!element_is0(P)) field_reinit_curve_twist(cc);
    element_clear(P);
  }

  mpz_set(param->q, cm->q);
  mpz_set(param->n, cm->n);
  mpz_set(param->h, cm->h);
  mpz_set(param->r, cm->r);
  element_to_mpz(param->a, curve_field_a_coeff(cc));
  element_to_mpz(param->b, curve_field_b_coeff(cc));
  param->k = cm->k;
  {
    mpz_t z;
    mpz_init(z);
    // Compute order of curve in F_q^k.
    // n = q - t + 1 hence t = q - n + 1
    mpz_sub(z, param->q, param->n);
    mpz_add_ui(z, z, 1);
    pbc_mpz_trace_n(z, param->q, z, param->k);
    mpz_pow_ui(param->nk, param->q, param->k);
    mpz_sub_ui(z, z, 1);
    mpz_sub(param->nk, param->nk, z);
    mpz_mul(z, param->r, param->r);
    mpz_divexact(param->hk, param->nk, z);
    mpz_clear(z);
  }
  field_clear(cc);
  field_clear(fp);
}
Пример #19
0
int main(){
	mpz_init( p);
	mpz_init( q);
	mpz_init( n);
	mpz_init( lambda);
	mpz_init( g);
	mpz_init( nn); // n squared 
	mpz_init( initNbMpz);
	mpz_init( gcdResult);
	mpz_init( lcmResult);
	mpz_init( tmpI);
	mpz_init( tmpII);
	mpz_init( p_1);
	mpz_init( q_1);

	//[Declaration]//mpz_t  r; // this is how to declare int in gmp
	//[initiallization]// mpz_init (r); // this is how i initialize the variables 
	//[Print]//gmp_printf ("%Zd\n", r); // this is how i print'em 
	//[set x = string]//mpz_set_str : https://gmplib.org/manual/Assigning-Integers.html#Assigning-Integers
	//[*]//void mpz_mul (mpz_t rop, const mpz_t op1, const mpz_t op2) 
	//[Quotient]//void mpz_cdiv_q (mpz_t q, const mpz_t n, const mpz_t d)
	//[Reminder]//void mpz_cdiv_r (mpz_t r, const mpz_t n, const mpz_t d)
	//[Exponentiation] //void mpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const mpz_t mod)

	//[GCD]void mpz_gcd (mpz_t rop, const mpz_t op1, const mpz_t op2)
	//void mpz_lcm (mpz_t rop, const mpz_t op1, const mpz_t op2)

	//void mpz_nextprime (mpz_t rop, const mpz_t op)
	// int mpz_probab_prime_p (const mpz_t n, int reps) // which uses Miller-Rabin probabilistic primality tests. 
	
	
	//printf("%s\n", initNb);
	
	

	/*****************PROMBLEM**************************/
	/*No matter how many times I apply the algo it seems to be not sure if it's Prime */
	/**********************************/
	       /******************/
	           /**********/
	             /*****/
	              /**/ 
	
	
	srand((unsigned) time(&t));
	keysGeneration();
	printf("what are you doin  dude!!\n");

	encrypt(6034);
	//IMPORTANT
	//I have to make sure that (m; which i want to encrypt) is smaller than n
	decryption();
	mpz_clear(p);
	mpz_clear(q);
	mpz_clear(n);
	mpz_clear(nn);
	mpz_clear(lambda);
	mpz_clear(g);
	mpz_clear(initNbMpz);
	mpz_clear(p_1);
	mpz_clear(q_1);
	mpz_clear(tmpI);
	mpz_clear(gcdResult);
	mpz_clear(lcmResult);
	mpz_clear(r);
	mpz_clear(c);

	return 0;
}
Пример #20
0
static void d_init_pairing(pairing_ptr pairing, void *data) {
  d_param_ptr param = data;
  pptr p;
  element_t a, b;
  element_t irred;
  int d = param->k / 2;
  int i;

  if (param->k % 2) pbc_die("k must be even");

  mpz_init(pairing->r);
  mpz_set(pairing->r, param->r);
  field_init_fp(pairing->Zr, pairing->r);
  pairing->map = cc_pairing;
  pairing->prod_pairings = cc_pairings_affine;
  pairing->is_almost_coddh = cc_is_almost_coddh;

  p = pairing->data = pbc_malloc(sizeof(*p));
  field_init_fp(p->Fq, param->q);
  element_init(a, p->Fq);
  element_init(b, p->Fq);
  element_set_mpz(a, param->a);
  element_set_mpz(b, param->b);
  field_init_curve_ab(p->Eq, a, b, pairing->r, param->h);

  field_init_poly(p->Fqx, p->Fq);
  element_init(irred, p->Fqx);
  poly_set_coeff1(irred, d);
  for (i = 0; i < d; i++) {
    element_set_mpz(element_item(irred, i), param->coeff[i]);
  }

  field_init_polymod(p->Fqd, irred);
  element_clear(irred);

  p->Fqd->nqr = pbc_malloc(sizeof(element_t));
  element_init(p->Fqd->nqr, p->Fqd);
  element_set_mpz(((element_t *) p->Fqd->nqr->data)[0], param->nqr);

  field_init_quadratic(p->Fqk, p->Fqd);

  // Compute constants involved in the final powering.
  if (param->k == 6) {
    mpz_ptr q = param->q;
    mpz_ptr z = pairing->phikonr;
    mpz_init(z);
    mpz_mul(z, q, q);
    mpz_sub(z, z, q);
    mpz_add_ui(z, z, 1);
    mpz_divexact(z, z, pairing->r);

    element_ptr e = p->xpowq;
    element_init(e, p->Fqd);
    element_set1(((element_t *) e->data)[1]);
    element_pow_mpz(e, e, q);

    element_init(p->xpowq2, p->Fqd);
    element_square(p->xpowq2, e);
  } else {
    mpz_init(p->tateexp);
    mpz_sub_ui(p->tateexp, p->Fqk->order, 1);
    mpz_divexact(p->tateexp, p->tateexp, pairing->r);
  }

  field_init_curve_ab_map(p->Etwist, p->Eq, element_field_to_polymod, p->Fqd, pairing->r, NULL);
  field_reinit_curve_twist(p->Etwist);

  mpz_t ndonr;
  mpz_init(ndonr);
  // ndonr temporarily holds the trace.
  mpz_sub(ndonr, param->q, param->n);
  mpz_add_ui(ndonr, ndonr, 1);
  // Negate it because we want the trace of the twist.
  mpz_neg(ndonr, ndonr);
  pbc_mpz_curve_order_extn(ndonr, param->q, ndonr, d);
  mpz_divexact(ndonr, ndonr, param->r);
  field_curve_set_quotient_cmp(p->Etwist, ndonr);
  mpz_clear(ndonr);

  element_init(p->nqrinv, p->Fqd);
  element_invert(p->nqrinv, field_get_nqr(p->Fqd));
  element_init(p->nqrinv2, p->Fqd);
  element_square(p->nqrinv2, p->nqrinv);

  pairing->G1 = p->Eq;
  pairing->G2 = p->Etwist;

  p->k = param->k;
  pairing_GT_init(pairing, p->Fqk);
  pairing->finalpow = cc_finalpow;

  // By default use affine coordinates.
  cc_miller_no_denom_fn = cc_miller_no_denom_affine;
  pairing->option_set = d_pairing_option_set;
  pairing->pp_init = d_pairing_pp_init;
  pairing->pp_clear = d_pairing_pp_clear;
  pairing->pp_apply = d_pairing_pp_apply;

  pairing->clear_func = d_pairing_clear;

  element_clear(a);
  element_clear(b);
}
int
aks (mpz_t n)
{
  mpz_t r;
  mpz_t a;
  mpz_t max_a;
  mpz_t gcd_rslt;
  mpz_t totient_r;
  mpf_t ftotient_r;
  mpf_t sqrt_rslt;
  mpf_t sqrt_rslt2;
  mpf_t temp;
  mpf_t temp2;
  sli_t logn;
/* For the sake of maple kernel */
  int argc = 0;
  char **argv;
  char err[2048];
  mpz_init (r);
  mpz_init (a);
  mpz_init (max_a);
  mpz_init (gcd_rslt);
  mpz_init (totient_r);
  mpf_init (ftotient_r);
  mpf_init (sqrt_rslt);
  mpf_init (sqrt_rslt2);
  mpf_init (temp);
  mpf_init (temp2);
/* 1. If (n = a^k for a in N and b > 1) output COMPOSITE */
  if (mpz_perfect_power_p (n) != 0)
    {
      printf ("Step 1 detected composite\n");
      return FALSE;
    }
/* 2. Find the smallest r such that or(n) > 4(log n)^2 */
  find_smallest_r (r, n);
  gmp_printf ("good r seems to be %Zd\n", r);
/* 3. If 1 < gcd(a, n) < n for some a <= r, output COMPOSITE */
/* for (a = 1; a <= r; a++) {
* gcd_rslt = gcd(a, n);
* if (gcd_rslt > 1 && gcd_rslt < n) {
* return FALSE;
* }
* }
*/
  for (mpz_set_ui (a, 1);
       mpz_cmp (a, r) < 0 || mpz_cmp (a, r) == 0; mpz_add_ui (a, a, 1))
    {
      mpz_gcd (gcd_rslt, a, n);
      if (mpz_cmp_ui (gcd_rslt, 1) > 0 && mpz_cmp (gcd_rslt, n) < 0)
	{
	  printf ("Step 3 detected composite\n");
	  return FALSE;
	}
    }
/* 4. If n <= r, output PRIME */
  if (mpz_cmp (n, r) < 0 || mpz_cmp (n, r) == 0)
    {
      printf ("Step 4 detected prime\n");
      return TRUE;
    }
/* 5. For a = 1 to floor(2*sqrt(totient(r))*(log n)
* if ( (X+a)^n != X^n + a (mod X^r-1, n) ), output COMPOSITE
*
* Choices of implementation to evaluate the polynomial equality:
* (1) Implement powermodreduce on polynomial ourselves (tough manly way)
* (2) Use MAPLE (not so manly, but less painful)
*/
/* Compute totient(r), since r is prime, this is simply r-1 */
  mpz_sub_ui (totient_r, r, 1);
/* Compute log n (ceilinged) */
  mpz_logbase2cl (&logn, n);
/* Compute sqrt(totient(r)) */
  mpf_set_z (ftotient_r, totient_r);
  mpf_sqrt (sqrt_rslt, ftotient_r);
/* Compute 2*sqrt(totient(r)) */
  mpf_mul_ui (sqrt_rslt2, sqrt_rslt, 2);
/* Compute 2*sqrt(totient(r))*(log n) */
  mpf_set (temp, sqrt_rslt2);
  mpf_set_si (temp2, logn);
  mpf_mul (temp, temp, temp2);
/* Finally, compute max_a, after lots of singing and dancing */
  mpf_floor (temp, temp);
  mpz_set_f (max_a, temp);
  gmp_printf ("max_a = %Zd\n", max_a);
/* Now evaluate the polynomial equality with the help of maple kernel */
/* Set up maple kernel incantations */
  MKernelVector kv;
  MCallBackVectorDesc cb = { textCallBack,
    0,				/* errorCallBack not used */
    0,				/* statusCallBack not used */
    0,				/* readLineCallBack not used */
    0,				/* redirectCallBack not used */
    0,				/* streamCallBack not used */
    0,				/* queryInterrupt not used */
    0				/* callBackCallBack not used */
  };
/* Initialize Maple */
  if ((kv = StartMaple (argc, argv, &cb, NULL, NULL, err)) == NULL)
    {
      printf ("Could not start Maple, %s\n", err);
      exit (666);
    }
/* Here comes the complexity and bottleneck */
/* for (a = 1; a <= max_a; a++) {
* if (!poly_eq_holds(kv, a, n, r)) {
* return FALSE;
* }
* }
*/
/* Make max_a only up to 5 */
  mpz_set_ui (max_a, 5);
  for (mpz_set_ui (a, 1);
       mpz_cmp (a, max_a) < 0 || mpz_cmp (a, max_a) == 0;
       mpz_add_ui (a, a, 1))
    {
      if (!poly_eq_holds (kv, a, n, r))
	{
	  printf ("Step 5 detected composite\n");
	  return FALSE;
	}
    }
/* 6. Output PRIME */
  printf ("Step 6 detected prime\n");
  return TRUE;
}
Пример #22
0
int
mpfr_set_str (mpfr_ptr x, __gmp_const char *str, int base, mp_rnd_t rnd_mode)
{
  mpz_t mantissa;
  int negative, inex;
  long k = 0;
  unsigned char c;
  long e;
  mp_prec_t q;
  mpfr_t y, z;

  if (base < 2 || base > 36)
    return 1;

  if (strcasecmp(str, "NaN") == 0)
    {
      MPFR_SET_NAN(x);
      /* MPFR_RET_NAN not used as the return value isn't a ternary value */
      __mpfr_flags |= MPFR_FLAGS_NAN;
      return 0;
    }

  negative = *str == '-';
  if (negative || *str == '+')
    str++;

  if (strcasecmp(str, "Inf") == 0)
    {
      MPFR_CLEAR_NAN(x);
      MPFR_SET_INF(x);
      if (negative)
        MPFR_SET_NEG(x);
      else
        MPFR_SET_POS(x);
      return 0;
    }

  mpz_init(mantissa);
  mpz_set_ui(mantissa, 0);

  while (*str == '0')
    str++; /* skip initial zeros */

  /* allowed characters are '0' to '0'+base-1 if base <= 10,
     and '0' to '9' plus 'a' to 'a'+base-11 if 10 < base <= 36 */
  while (c = *str,
         (isdigit(c) && c < '0' + base) ||
         (islower(c) && c < 'a'-10 + base))
    {
      str++;
      mpz_mul_ui(mantissa, mantissa, base);
      mpz_add_ui(mantissa, mantissa, isdigit(c) ? c - '0' : c - ('a'-10));
    }

  /* k is the number of non-zero digits before the decimal point */

  if (*str == '.')
    {
      str++;
      while (c = *str,
             (isdigit(c) && c < '0' + base) ||
             (islower(c) && c < 'a'-10 + base))
	{
          if (k == LONG_MAX)
            {
              mpz_clear(mantissa);
              return -1;
            }
	  k++;
	  str++;
          mpz_mul_ui(mantissa, mantissa, base);
          mpz_add_ui(mantissa, mantissa, isdigit(c) ? c - '0' : c - ('a'-10));
	}
    }

  if (*str == '\0') /* no exponent */
    {
      e = -k;
    }
  else if ((base <= 10 && (*str == 'e' || *str == 'E')) || *str == '@')
    {
      char *endptr;

      if (*++str == '\0') /* exponent character but no exponent */
        {
          mpz_clear(mantissa);
          return 1;
        }

      errno = 0;
      e = strtol(str, &endptr, 10); /* signed exponent after 'e', 'E' or '@' */
      if (*endptr != '\0')
        {
          mpz_clear(mantissa);
          return 1;
        }
      if (errno)
        {
          mpz_clear(mantissa);
          return -1;
        }

      if (e < 0 && (unsigned long) e - k < (unsigned long) LONG_MIN)
        {
          mpz_clear(mantissa);
          return -1;
        }
      e -= k;
    }
  else /* unexpected character */
    {
      mpz_clear(mantissa);
      return 1;
    }

  /* the number is mantissa*base^expn */

  q = MPFR_PREC(x) & ~(mp_prec_t) (BITS_PER_MP_LIMB - 1);
  mpfr_init(y);
  mpfr_init(z);

  do
    {
      q += BITS_PER_MP_LIMB;
      mpfr_set_prec(y, q);
      mpfr_set_z(y, mantissa, GMP_RNDN); /* error <= 1/2*ulp(y) */

      mpfr_set_prec(z, q);
      if (e > 0)
        {
          inex = mpfr_ui_pow_ui(z, base, e, GMP_RNDN);
          mpfr_mul(y, y, z, GMP_RNDN);
        }
      else if (e < 0)
        {
          inex = mpfr_ui_pow_ui(z, base, -e, GMP_RNDN);
          mpfr_div(y, y, z, GMP_RNDN);
        }
      else
        inex = 1;
      if (negative)
        mpfr_neg(y, y, GMP_RNDN);
    }
  while (mpfr_can_round(y, q-inex, GMP_RNDN, rnd_mode, MPFR_PREC(x))==0
         && q<=2*MPFR_PREC(x));

  mpfr_set(x, y, rnd_mode);

  mpz_clear(mantissa);
  mpfr_clear(y);
  mpfr_clear(z);
  return 0;
}
Пример #23
0
static void
test_specialz (int (*mpfr_func)(mpfr_ptr, mpfr_srcptr, mpz_srcptr, mp_rnd_t),
               void (*mpz_func)(mpz_ptr, mpz_srcptr, mpz_srcptr),
               const char *op)
{
  mpfr_t x1, x2;
  mpz_t  z1, z2;
  int res;

  mpfr_inits2 (128, x1, x2, (void *) 0);
  mpz_init (z1); mpz_init(z2);
  mpz_fac_ui (z1, 19); /* 19!+1 fits perfectly in a 128 bits mantissa */
  mpz_add_ui (z1, z1, 1);
  mpz_fac_ui (z2, 20); /* 20!+1 fits perfectly in a 128 bits mantissa */
  mpz_add_ui (z2, z2, 1);

  res = mpfr_set_z(x1, z1, GMP_RNDN);
  if (res)
    {
      printf("Specialz %s: set_z1 error\n", op);
      exit(1);
    }
  mpfr_set_z (x2, z2, GMP_RNDN);
  if (res)
    {
      printf("Specialz %s: set_z2 error\n", op);
      exit(1);
    }

  /* (19!+1) * (20!+1) fits in a 128 bits number */
  res = mpfr_func(x1, x1, z2, GMP_RNDN);
  if (res)
    {
      printf("Specialz %s: wrong inexact flag.\n", op);
      exit(1);
    }
  mpz_func(z1, z1, z2);
  res = mpfr_set_z (x2, z1, GMP_RNDN);
  if (res)
    {
      printf("Specialz %s: set_z2 error\n", op);
      exit(1);
    }
  if (mpfr_cmp(x1, x2))
    {
      printf("Specialz %s: results differ.\nx1=", op);
      mpfr_print_binary(x1);
      printf("\nx2=");
      mpfr_print_binary(x2);
      printf ("\nZ2=");
      mpz_out_str (stdout, 2, z1);
      putchar('\n');
      exit(1);
    }

  mpz_set_ui (z1, 1);
  mpz_set_ui (z2, 0);
  mpfr_set_ui (x1, 1, GMP_RNDN);
  mpz_func (z1, z1, z2);
  res = mpfr_func(x1, x1, z2, GMP_RNDN);
  mpfr_set_z (x2, z1, GMP_RNDN);
  if (mpfr_cmp(x1, x2))
    {
      printf("Specialz %s: results differ(2).\nx1=", op);
      mpfr_print_binary(x1);
      printf("\nx2=");
      mpfr_print_binary(x2);
      putchar('\n');
      exit(1);
    }

  mpz_clear (z1); mpz_clear(z2);
  mpfr_clears (x1, x2, (void *) 0);
}
Пример #24
0
/* Compute the first 2^m terms from the hypergeometric series
   with x = p / 2^r */
static int
GENERIC (mpfr_ptr y, mpz_srcptr p, long r, int m)
{
  unsigned long n,i,k,j,l;
  int is_p_one;
  mpz_t* P,*S;
#ifdef A
  mpz_t *T;
#endif
  mpz_t* ptoj;
#ifdef R_IS_RATIONAL
  mpz_t* qtoj;
  mpfr_t tmp;
#endif
  mp_exp_t diff, expo;
  mp_prec_t precy = MPFR_PREC(y);
  MPFR_TMP_DECL(marker);

  MPFR_TMP_MARK(marker);
  MPFR_CLEAR_FLAGS(y);
  n = 1UL << m;
  P = (mpz_t*) MPFR_TMP_ALLOC ((m+1) * sizeof(mpz_t));
  S = (mpz_t*) MPFR_TMP_ALLOC ((m+1) * sizeof(mpz_t));
  ptoj = (mpz_t*) MPFR_TMP_ALLOC ((m+1) * sizeof(mpz_t)); /* ptoj[i] = mantissa^(2^i) */
#ifdef A
  T = (mpz_t*) MPFR_TMP_ALLOC ((m+1) * sizeof(mpz_t));
#endif
#ifdef R_IS_RATIONAL
  qtoj = (mpz_t*) MPFR_TMP_ALLOC ((m+1) * sizeof(mpz_t));
#endif
  for (i = 0 ; i <= m ; i++)
    {
      mpz_init (P[i]);
      mpz_init (S[i]);
      mpz_init (ptoj[i]);
#ifdef R_IS_RATIONAL
      mpz_init (qtoj[i]);
#endif
#ifdef A
      mpz_init (T[i]);
#endif
    }
  mpz_set (ptoj[0], p);
#ifdef C
#  if C2 != 1
  mpz_mul_ui (ptoj[0], ptoj[0], C2);
#  endif
#endif
  is_p_one = mpz_cmp_ui(ptoj[0], 1) == 0;
#ifdef A
#  ifdef B
  mpz_set_ui (T[0], A1 * B1);
#  else
  mpz_set_ui (T[0], A1);
#  endif
#endif
  if (!is_p_one)
    for (i = 1 ; i < m ; i++)
      mpz_mul (ptoj[i], ptoj[i-1], ptoj[i-1]);
#ifdef R_IS_RATIONAL
  mpz_set_si (qtoj[0], r);
  for (i = 1 ; i <= m ; i++)
    mpz_mul(qtoj[i], qtoj[i-1], qtoj[i-1]);
#endif
  mpz_set_ui (P[0], 1);
  mpz_set_ui (S[0], 1);

  k = 0;
  for (i = 1 ; i < n ; i++) {
    k++;

#ifdef A
#  ifdef B
    mpz_set_ui (T[k], (A1 + A2*i)*(B1+B2*i));
#  else
    mpz_set_ui (T[k], A1 + A2*i);
#  endif
#endif

#ifdef C
#  ifdef NO_FACTORIAL
    mpz_set_ui (P[k], (C1 + C2 * (i-1)));
    mpz_set_ui (S[k], 1);
#  else
    mpz_set_ui (P[k], (i+1) * (C1 + C2 * (i-1)));
    mpz_set_ui (S[k], i+1);
#  endif
#else
#  ifdef NO_FACTORIAL
    mpz_set_ui (P[k], 1);
#  else
    mpz_set_ui (P[k], i+1);
#  endif
    mpz_set (S[k], P[k]);
#endif

    for (j = i+1, l = 0 ; (j & 1) == 0 ; l++, j>>=1, k--) {
      if (!is_p_one)
        mpz_mul (S[k], S[k], ptoj[l]);
#ifdef A
#  ifdef B
#    if (A2*B2) != 1
      mpz_mul_ui (P[k], P[k], A2*B2);
#    endif
#  else
#    if A2 != 1
      mpz_mul_ui (P[k], P[k], A2);
#  endif
#endif
      mpz_mul (S[k], S[k], T[k-1]);
#endif
      mpz_mul (S[k-1], S[k-1], P[k]);
#ifdef R_IS_RATIONAL
      mpz_mul (S[k-1], S[k-1], qtoj[l]);
#else
      mpz_mul_2exp (S[k-1], S[k-1], r*(1<<l));
#endif
      mpz_add (S[k-1], S[k-1], S[k]);
      mpz_mul (P[k-1], P[k-1], P[k]);
#ifdef A
      mpz_mul (T[k-1], T[k-1], T[k]);
#endif
    }
  }

  diff = mpz_sizeinbase(S[0],2) - 2*precy;
  expo = diff;
  if (diff >= 0)
    mpz_div_2exp(S[0],S[0],diff);
  else
    mpz_mul_2exp(S[0],S[0],-diff);
  diff = mpz_sizeinbase(P[0],2) - precy;
  expo -= diff;
  if (diff >=0)
    mpz_div_2exp(P[0],P[0],diff);
  else
    mpz_mul_2exp(P[0],P[0],-diff);

  mpz_tdiv_q(S[0], S[0], P[0]);
  mpfr_set_z(y, S[0], GMP_RNDD);
  MPFR_SET_EXP (y, MPFR_GET_EXP (y) + expo);

#ifdef R_IS_RATIONAL
  /* exact division */
  mpz_div_ui (qtoj[m], qtoj[m], r);
  mpfr_init2 (tmp, MPFR_PREC(y));
  mpfr_set_z (tmp, qtoj[m] , GMP_RNDD);
  mpfr_div (y, y, tmp, GMP_RNDD);
  mpfr_clear (tmp);
#else
  mpfr_div_2ui(y, y, r*(i-1), GMP_RNDN);
#endif
  for (i = 0 ; i <= m ; i++)
    {
      mpz_clear (P[i]);
      mpz_clear (S[i]);
      mpz_clear (ptoj[i]);
#ifdef R_IS_RATIONAL
      mpz_clear (qtoj[i]);
#endif
#ifdef A
      mpz_clear (T[i]);
#endif
    }
  MPFR_TMP_FREE (marker);
  return 0;
}
Пример #25
0
void field_init_curve_ab(field_ptr f, element_ptr a, element_ptr b, mpz_t order, mpz_t cofac) {
  /*
  if (element_is0(a)) {
    c->double_nocheck = cc_double_no_check_ais0;
  } else {
    c->double_nocheck = cc_double_no_check;
  }
  */
  curve_data_ptr cdp;
  field_init(f);
  mpz_set(f->order, order);
  f->data = pbc_malloc(sizeof(*cdp));
  cdp = (curve_data_ptr)f->data;
  cdp->field = a->field;
  element_init(cdp->a, cdp->field);
  element_init(cdp->b, cdp->field);
  element_set(cdp->a, a);
  element_set(cdp->b, b);

  f->init = curve_init;
  f->clear = curve_clear;
  f->neg = f->invert = curve_invert;
  f->square = f->doub = curve_double;
  f->multi_doub = multi_double;
  f->add = f->mul = curve_mul;
  f->multi_add = multi_add;
  f->mul_mpz = element_pow_mpz;
  f->cmp = curve_cmp;
  f->set0 = f->set1 = curve_set1;
  f->is0 = f->is1 = curve_is1;
  f->sign = curve_sign;
  f->set = curve_set;
  f->random = curve_random_pointmul;
  //f->random = curve_random_solvefory;
  f->from_hash = curve_from_hash;
  f->out_str = curve_out_str;
  f->snprint = curve_snprint;
  f->set_multiz = curve_set_multiz;
  f->set_str = curve_set_str;
  f->field_clear = field_clear_curve;
  if (cdp->field->fixed_length_in_bytes < 0) {
    f->length_in_bytes = curve_length_in_bytes;
  } else {
    f->fixed_length_in_bytes = 2 * cdp->field->fixed_length_in_bytes;
  }
  f->to_bytes = curve_to_bytes;
  f->from_bytes = curve_from_bytes;
  f->out_info = curve_out_info;
  f->item_count = curve_item_count;
  f->item = curve_item;
  f->get_x = curve_get_x;
  f->get_y = curve_get_y;

  if (mpz_odd_p(order)) {
    f->is_sqr = odd_curve_is_sqr;
  } else {
    f->is_sqr = even_curve_is_sqr;
  }

  element_init(cdp->gen_no_cofac, f);
  element_init(cdp->gen, f);
  curve_random_no_cofac_solvefory(cdp->gen_no_cofac);
  if (cofac) {
    cdp->cofac = (mpz_ptr)pbc_malloc(sizeof(mpz_t));
    mpz_init(cdp->cofac);
    mpz_set(cdp->cofac, cofac);
    element_mul_mpz(cdp->gen, cdp->gen_no_cofac, cofac);
  } else{
    cdp->cofac = NULL;
    element_set(cdp->gen, cdp->gen_no_cofac);
  }
  cdp->quotient_cmp = NULL;
}
Пример #26
0
int
mpfr_grandom (mpfr_ptr rop1, mpfr_ptr rop2, gmp_randstate_t rstate,
              mpfr_rnd_t rnd)
{
  int inex1, inex2, s1, s2;
  mpz_t x, y, xp, yp, t, a, b, s;
  mpfr_t sfr, l, r1, r2;
  mpfr_prec_t tprec, tprec0;

  inex2 = inex1 = 0;

  if (rop2 == NULL) /* only one output requested. */
    {
      tprec0 = MPFR_PREC (rop1);
    }
  else
    {
      tprec0 = MAX (MPFR_PREC (rop1), MPFR_PREC (rop2));
    }

  tprec0 += 11;

  /* We use "Marsaglia polar method" here (cf.
     George Marsaglia, Normal (Gaussian) random variables for supercomputers
     The Journal of Supercomputing, Volume 5, Number 1, 49–55
     DOI: 10.1007/BF00155857).

     First we draw uniform x and y in [0,1] using mpz_urandomb (in
     fixed precision), and scale them to [-1, 1].
  */

  mpz_init (xp);
  mpz_init (yp);
  mpz_init (x);
  mpz_init (y);
  mpz_init (t);
  mpz_init (s);
  mpz_init (a);
  mpz_init (b);
  mpfr_init2 (sfr, MPFR_PREC_MIN);
  mpfr_init2 (l, MPFR_PREC_MIN);
  mpfr_init2 (r1, MPFR_PREC_MIN);
  if (rop2 != NULL)
    mpfr_init2 (r2, MPFR_PREC_MIN);

  mpz_set_ui (xp, 0);
  mpz_set_ui (yp, 0);

  for (;;)
    {
      tprec = tprec0;
      do
        {
          mpz_urandomb (xp, rstate, tprec);
          mpz_urandomb (yp, rstate, tprec);
          mpz_mul (a, xp, xp);
          mpz_mul (b, yp, yp);
          mpz_add (s, a, b);
        }
      while (mpz_sizeinbase (s, 2) > tprec * 2); /* x^2 + y^2 <= 2^{2tprec} */

      for (;;)
        {
          /* FIXME: compute s as s += 2x + 2y + 2 */
          mpz_add_ui (a, xp, 1);
          mpz_add_ui (b, yp, 1);
          mpz_mul (a, a, a);
          mpz_mul (b, b, b);
          mpz_add (s, a, b);
          if ((mpz_sizeinbase (s, 2) <= 2 * tprec) ||
              ((mpz_sizeinbase (s, 2) == 2 * tprec + 1) &&
               (mpz_scan1 (s, 0) == 2 * tprec)))
            goto yeepee;
          /* Extend by 32 bits */
          mpz_mul_2exp (xp, xp, 32);
          mpz_mul_2exp (yp, yp, 32);
          mpz_urandomb (x, rstate, 32);
          mpz_urandomb (y, rstate, 32);
          mpz_add (xp, xp, x);
          mpz_add (yp, yp, y);
          tprec += 32;

          mpz_mul (a, xp, xp);
          mpz_mul (b, yp, yp);
          mpz_add (s, a, b);
          if (mpz_sizeinbase (s, 2) > tprec * 2)
            break;
        }
    }
 yeepee:

  /* FIXME: compute s with s -= 2x + 2y + 2 */
  mpz_mul (a, xp, xp);
  mpz_mul (b, yp, yp);
  mpz_add (s, a, b);
  /* Compute the signs of the output */
  mpz_urandomb (x, rstate, 2);
  s1 = mpz_tstbit (x, 0);
  s2 = mpz_tstbit (x, 1);
  for (;;)
    {
      /* s = xp^2 + yp^2 (loop invariant) */
      mpfr_set_prec (sfr, 2 * tprec);
      mpfr_set_prec (l, tprec);
      mpfr_set_z (sfr, s, MPFR_RNDN); /* exact */
      mpfr_mul_2si (sfr, sfr, -2 * tprec, MPFR_RNDN); /* exact */
      mpfr_log (l, sfr, MPFR_RNDN);
      mpfr_neg (l, l, MPFR_RNDN);
      mpfr_mul_2si (l, l, 1, MPFR_RNDN);
      mpfr_div (l, l, sfr, MPFR_RNDN);
      mpfr_sqrt (l, l, MPFR_RNDN);

      mpfr_set_prec (r1, tprec);
      mpfr_mul_z (r1, l, xp, MPFR_RNDN);
      mpfr_div_2ui (r1, r1, tprec, MPFR_RNDN); /* exact */
      if (s1)
        mpfr_neg (r1, r1, MPFR_RNDN);
      if (MPFR_CAN_ROUND (r1, tprec - 2, MPFR_PREC (rop1), rnd))
        {
          if (rop2 != NULL)
            {
              mpfr_set_prec (r2, tprec);
              mpfr_mul_z (r2, l, yp, MPFR_RNDN);
              mpfr_div_2ui (r2, r2, tprec, MPFR_RNDN); /* exact */
              if (s2)
                mpfr_neg (r2, r2, MPFR_RNDN);
              if (MPFR_CAN_ROUND (r2, tprec - 2, MPFR_PREC (rop2), rnd))
                break;
            }
          else
            break;
        }
      /* Extend by 32 bits */
      mpz_mul_2exp (xp, xp, 32);
      mpz_mul_2exp (yp, yp, 32);
      mpz_urandomb (x, rstate, 32);
      mpz_urandomb (y, rstate, 32);
      mpz_add (xp, xp, x);
      mpz_add (yp, yp, y);
      tprec += 32;
      mpz_mul (a, xp, xp);
      mpz_mul (b, yp, yp);
      mpz_add (s, a, b);
    }
  inex1 = mpfr_set (rop1, r1, rnd);
  if (rop2 != NULL)
    {
      inex2 = mpfr_set (rop2, r2, rnd);
      inex2 = mpfr_check_range (rop2, inex2, rnd);
    }
  inex1 = mpfr_check_range (rop1, inex1, rnd);

  if (rop2 != NULL)
    mpfr_clear (r2);
  mpfr_clear (r1);
  mpfr_clear (l);
  mpfr_clear (sfr);
  mpz_clear (b);
  mpz_clear (a);
  mpz_clear (s);
  mpz_clear (t);
  mpz_clear (y);
  mpz_clear (x);
  mpz_clear (yp);
  mpz_clear (xp);

  return INEX (inex1, inex2);
}
Пример #27
0
int main(int argc, char *argv[])
{
  if(argc != 4)
  {
      printf("Three arguments required\n");
      printf("Usage: %s a b c calculates pi(a*b^c)\n", argv[0]);
      exit(1);
  }

  //Legacy GMP code below; the input must fit in a 64 bit unsigned integer
  mpz_t n;
  mpz_init(n);

  mpz_ui_pow_ui(n, atol(argv[2]), atol(argv[3]));
  mpz_mul_ui(n, n, atol(argv[1]));
  uint64_t n2 = mpz_get_ui(n);
  mpz_clear(n);

  uint64_t* s = calloc(n2/64+3, sizeof(uint64_t));
  assert(s != NULL);

  //for wheel mod 30
  uint64_t wheel_pattern[15];
  init(wheel_pattern);
  uint64_t k;
  for(k=0; k <= n2/64; k++) s[k] = wheel_pattern[k%15];

  uint64_t sieve_to = floor(sqrt(n2));

  uint64_t i,j;


  i=7;							//7 is the first number > 1 which is relatively prime to 30
  while (i <= sieve_to)
  {
    if(TEST(s, i) != 0)					//Only sieve by primes
    {
	switch(i%30)
	{
	case 1:
	    for(j=i*i; j<=n2; j+= 30*i)  CLEAR(s, j);        
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+10); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+16); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+22); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+28); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 7:
	    for(j=i*i; j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+4); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+10); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+16); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+22); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 11:
	    for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+2); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+8); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+20); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+26); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 13:
	    for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+4); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+10); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+16); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+28); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 17:
	    for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+2); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+14); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+20); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+26); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 19:
	    for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+4); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+10); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+22); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+28); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 23:
	    for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+6); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+8); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+14); j<=n2; j+= 30*i)  CLEAR(s, j);   
	    for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);    
	    for(j=i*(i+20); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);  
	    for(j=i*(i+26); j<=n2; j+= 30*i)  CLEAR(s, j);  
        break;

	case 29:
            for(j=i*(i+0); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+2); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+8); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+12); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+14); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+18); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+20); j<=n2; j+= 30*i)  CLEAR(s, j);
            for(j=i*(i+24); j<=n2; j+= 30*i)  CLEAR(s, j);
	break;

	default:
	    printf("Error\n");
	    exit(1);

	}
    }
    i += get_next(i);						//Advance pointer to the next number
  }



  #if 0
  for(i=0; i<=n2; i++)
    if(TEST(s,i)>0) printf("%" PRIu64 "\n",i);
  #endif 

  //Note ridiculous macro format required to print unit64_t without generating a compiler warning                                              
  printf("%" PRIu64 "\n", count_bits(s, 0, n2)+2);
  free(s);

  return(0);
}
Пример #28
0
void benchmark_optimize_log()
{
    int REPS;
    int prec;
    int i, k, r, J, best_r, best_J;
    double best_time, best_here;
    double t1, t2, elapsed;
    double mpfr_time;
    int accuracy, min_accuracy;

    mpz_t x, y, dummy;
    mpfr_t mx, my;

    mpfr_init(mx);
    mpfr_init(my);

    mpz_init(x);
    mpz_init(y);
    mpz_init(dummy);

    printf(" prec   acc   J   r     mpfr     this   faster\n");

    for (prec=53; prec<6000; prec+=prec/4)
    {
        if (prec < 300)
            REPS = 100;
        else if (prec < 600)
            REPS = 50;
        else if (prec < 1200)
            REPS = 10;
        else
            REPS = 2;

        mpz_set_ui(x, 137);
        mpz_mul_2exp(x, x, prec);
        mpz_div_ui(x, x, 100);

        min_accuracy = prec;
        best_time = 1e100;
        best_r = 0;
        best_J = 0;

        mpfr_set_prec(mx, prec);
        mpfr_set_prec(my, prec);
        mpfr_set_str(mx, "1.37", 10, GMP_RNDN);

        mpfr_time = 1e100;
        for (i=0; i<10; i++)
        {
            t1 = timing();
            for (k=0; k<REPS; k++)
            {
                mpfr_log(my, mx, GMP_RNDN);
            }
            t2 = timing();
            elapsed = (t2-t1)/REPS;
            if (elapsed < mpfr_time)
                mpfr_time = elapsed;
        }

        for (J=1; J<MAX_SERIES_STEPS; J++)
        {
            for (r=0; r*r<prec+30; r++)
            {
                for (i=0; i<3; i++)
                {
                    t1 = timing();
                    for (k=0; k<REPS; k++)
                    {
                        log_series(y, x, prec, r, J, 1);
                    }
                    t2 = timing();
                    elapsed = (t2-t1) / REPS;

                    if (elapsed < best_time)
                    {
                        best_time = elapsed;
                        best_r = r;
                        best_J = J;
                    }
                }

                mpfr_set_z(mx, y, GMP_RNDN);
                mpfr_div_2ui(mx, mx, prec, GMP_RNDN);
                //mpfr_printf("Value:  %Rf\n", mx);
                mpfr_sub(mx, mx, my, GMP_RNDN);
                mpfr_abs(mx, mx, GMP_RNDN);
                if (!mpfr_zero_p(mx))
                {
                    accuracy = -(int)mpfr_get_exp(mx)+1;
                    if (accuracy < min_accuracy)
                    {
                        min_accuracy = accuracy;
                    }
                }
            }
        }

        mpfr_time *= 1000;
        best_time *= 1000;

        printf("%5d %5d %3d %3d %8d %8d   %.3f\n", prec, min_accuracy, best_J, best_r,
            (int)mpfr_time, (int)best_time, mpfr_time/best_time);

    }

    mpfr_clear(mx);
    mpfr_clear(my);

    mpz_clear(x);
    mpz_clear(y);
    mpz_clear(dummy);

}
Пример #29
0
C_BigInt::C_BigInt (void) :
mGMPint () {
  mpz_init (mGMPint) ;
}
Пример #30
0
int main()
{
    slong iter;
    flint_rand_t state;

    flint_printf("set_round_mpz....");
    fflush(stdout);

    flint_randinit(state);

    {
        arf_t x, y;

        arf_init(x);
        arf_init(y);

        for (iter = 0; iter < 100000 * arb_test_multiplier(); iter++)
        {
            slong bits1, bits2;
            int ret1, ret2;
            fmpz_t a;
            mpz_t b;
            mpfr_t g;
            arf_rnd_t rnd;

            bits1 = 1 + n_randint(state, 1000);
            bits2 = 2 + n_randint(state, 1000);

            if (n_randint(state, 100) == 0)
                bits2 = ARF_PREC_EXACT;

            fmpz_init(a);
            mpz_init(b);
            mpfr_init2(g, FLINT_MIN(bits2, 10000));

            if (n_randint(state, 100) == 0)
            {
                arf_clear(x);
                arf_clear(y);
                arf_init(x);
                arf_init(y);
            }

            /* dirty output variables */
            if (n_randint(state, 2))
            {
                arf_randtest_special(x, state, 1 + n_randint(state, 1000),
                    1 + n_randint(state, 100));
                arf_randtest_special(y, state, 1 + n_randint(state, 1000),
                    1 + n_randint(state, 100));
            }

            fmpz_randtest(a, state, bits1);
            fmpz_get_mpz(b, a);

            switch (n_randint(state, 5))
            {
                case 0: rnd = ARF_RND_DOWN; break;
                case 1: rnd = ARF_RND_UP; break;
                case 2: rnd = ARF_RND_FLOOR; break;
                case 3: rnd = ARF_RND_CEIL; break;
                default: rnd = ARF_RND_NEAR; break;
            }

            ret1 = arf_set_round_mpz(x, b, bits2, rnd);
            ret2 = mpfr_set_z(g, b, arf_rnd_to_mpfr(rnd));
            arf_set_mpfr(y, g);
            arf_equal(x, y);

            if (!arf_equal(x, y) || ((ret1 == ARF_RESULT_EXACT) != (ret2 == 0)))
            {
                flint_printf("FAIL\n\n");
                flint_printf("bits1: %wd\n", bits1);
                flint_printf("bits2: %wd\n", bits2);
                flint_printf("a = "); fmpz_print(a); flint_printf("\n\n");
                flint_printf("x = "); arf_print(x); flint_printf("\n\n");
                flint_printf("y = "); arf_print(y); flint_printf("\n\n");
                flint_printf("ret1 = %d, ret2 = %d\n\n", ret1, ret2);
                abort();
            }

            fmpz_clear(a);
            mpz_clear(b);
            mpfr_clear(g);
        }

        arf_clear(x);
        arf_clear(y);
    }

    flint_randclear(state);
    flint_cleanup();
    flint_printf("PASS\n");
    return EXIT_SUCCESS;
}