Пример #1
0
BVValue BVValue::divideUnsigned(const BVValue& _other, bool _returnRemainder) const {
	assert(width() == _other.width());
	assert(Base(_other) != Base(_other.width(), 0));

	Base quotient(width());
	std::size_t quotientIndex = 0;
	Base divisor = static_cast<Base>(_other);
	Base remainder(mValue);

	while (!divisor[divisor.size() - 1] && remainder > divisor) {
		++quotientIndex;
		divisor <<= 1;
	}

	while (true) {
		if (remainder >= divisor) {
			quotient[quotientIndex] = true;
			// substract divisor from remainder
			bool carry = false;
			for (std::size_t i = divisor.find_first(); i < remainder.size(); ++i) {
				bool newRemainderI = (remainder[i] != divisor[i]) != carry;
				carry = (remainder[i] && carry && divisor[i]) || (!remainder[i] && (carry || divisor[i]));
				remainder[i] = newRemainderI;
			}
		}
		if (quotientIndex == 0) {
			break;
		}
		divisor >>= 1;
		--quotientIndex;
	}

	return BVValue(_returnRemainder ? std::move(remainder) : std::move(quotient));
}
Пример #2
0
void
ACE_Stats::mean (ACE_Stats_Value &m,
                 const ACE_UINT32 scale_factor)
{
  if (number_of_samples_ > 0)
    {
      const ACE_UINT64 ACE_STATS_INTERNAL_OFFSET =
        ACE_UINT64_LITERAL (0x100000000);

      ACE_UINT64 sum = ACE_STATS_INTERNAL_OFFSET;
      ACE_Unbounded_Queue_Iterator<ACE_INT32> i (samples_);
      while (! i.done ())
        {
          ACE_INT32 *sample;
          if (i.next (sample))
            {
              sum += *sample;
              i.advance ();
            }
        }

      // sum_ was initialized with ACE_STATS_INTERNAL_OFFSET, so
      // subtract that off here.
      quotient (sum - ACE_STATS_INTERNAL_OFFSET,
                number_of_samples_ * scale_factor,
                m);
    }
  else
    {
      m.whole (0);
      m.fractional (0);
    }
}
Пример #3
0
    std::pair<polynomial, polynomial> quo_rem (polynomial divisor) const {
        /* Degrees of the remainder and quotient. */
        int kd = divisor.degree();
        int kr = kd - 1;
        int kq = degree() - kd;

        std::vector<double> remainder (kr + 1);
        std::vector<double> quotient (kq + 1);

        auto dbegin = divisor.coefficients.crbegin() + 1;
        auto dend = divisor.coefficients.crend();
        auto qbegin = quotient.end();
        auto qend = quotient.end();

        for (int i = kq; 0 <= i; i--) {
            quotient[i] = (coefficients[kd+i] - ip(dbegin, dend, qbegin, qend)) / divisor[kd];
            --qbegin;
        }

        for (int i = kr; 0 <= i; i--) {
            remainder[i] = coefficients[i] - ip(dbegin, dend, qbegin, qend);
            ++dbegin;
        }

        return { polynomial { quotient }, polynomial { remainder } };
    }
Пример #4
0
        static void longdivide( MLDiv const &x, MLDiv const &y,
                                MLDiv &q, MLDiv &r,
                                UBIG n, UBIG m ) {
            MLDiv d;
            MLDiv dq;
            MLDiv tr;
            UBIG f;
            int k;
            UBIG qt;

            assert( 2 <= m && m <= n && n <= w );
            f = b / ( y.d[m-1] + 1 );
            product( tr, x, f );
            product( d, y, f );
            zero( q );
            for( k = n-m; k >= 0; --k ) {
                assert( 2 <= m && m <= (k+m) && (k+m) <= n && n <= w );
                qt = trial( tr, d, k, m );
                product( dq, d, qt );
                if( smaller( tr, dq, k, m ) ) {
                    --qt;
                    product( dq, d, qt );
                }
                q.d[k] = qt;
                difference( tr, dq, k, m );
            }
            quotient( r, tr, f );
        }
Пример #5
0
        static void division( MLDiv const &x, MLDiv const &y,
                              MLDiv &q, MLDiv &r ) {
            UBIG m;
            UBIG n;
            UBIG y1;

            m = length( y );
            if( m == 1 ) {
                y1 = y.d[ m - 1 ];
                if( y1 > 0 ) {
                    quotient( q, x, y1 );
                    remainder( r, x, y1 );
                } else {
                    fatal( "divide by 0" );
                }
            } else {
                n = length( x );
                if( m > n ) {
                    zero( q );
                    r = x;
                } else {
                    assert( 2 <= m && m <= n && n <= w );
                    longdivide( x, y, q, r, n, m );
                }
            }
        }
Пример #6
0
CSysVector CSysVector::operator/(const double & val) const {
  
  /*--- use copy constructor and compound scalar
   division-assignment ---*/
  CSysVector quotient(*this);
  quotient /= val;
  return quotient;
}
Пример #7
0
LispObject* ModFloat( LispObject* int1, LispObject* int2, LispEnvironment& aEnvironment,
                        int aPrecision)
{
    ANumber quotient(static_cast<int>(0));
    ANumber remainder(static_cast<int>(0));
    DivideInteger( quotient, remainder, int1->String()->c_str(), int2->String()->c_str(), aPrecision);
    return FloatToString(remainder, aEnvironment,10);

}
Пример #8
0
void bar ()
{
    FiWord	quo;
    FiWord	rem;

    quotient(37, 5, &quo, &rem);

    print(quo);
    print(rem);
}
int main(int argc, char *argv[])
{
    std::cout << "Hello Mathematics and Generic Programming!" << std::endl;
    std::cout << "quotient test1: " << (quotient(5.0, 2.0) == 2 ? "pass" : "fail") << '\n';
    std::cout << "quotient_remainder test1: " << (quotient_remainder(8.3, 3.0) == std::make_pair(2, 2.3) ? "pass" : "fail") << "\n";
    const auto res = quotient_remainder(8.3, 3.0);
    std::cout << "quotient_remainder test1a: " << (res.first == 2) << '\n';
    std::cout << "quotient_remainder test1b: " << (res.second )
    std::cout << "f:" << res.first << " s:" << res.second << "\n";
    return 0;
}
Пример #10
0
auto search(uint32_t limit, const PrimeNumbers &primes) {
    const size_t iteration_limit = 10000;

    auto initial = initial_candidate(limit, primes);
    Components components = {initial, initial};

    for(size_t i=0;components.size() && i<iteration_limit;++i,components=next(components,initial,limit,primes)) {
        auto fraction = quotient(components);

        if(is_permuted_pair(fraction.p(),fraction.q())) {
            if(!util::test_mode()) {
                fmt::print("[{}] {}x{} -> {} ({})\n",i,
                                                *components[0],
                                                *components[1],
                                                 fraction,
                                                 static_cast<double>(fraction));
            }
            return std::make_tuple(true,fraction);
        };
    }

    return std::make_tuple(false,quotient(Components{}));
}
int main() {
  std::cout << "gcm0(121, 66) = " << gcm0(121, 66) << std::endl;
  std::cout << "gcm1(121, 66) = " << gcm1(121, 66) << std::endl;
  std::cout << "gcm(121, 66) = " << gcm(121, 66) << std::endl;
  std::cout << "fast_segment_gcm(121, 66) = " << fast_segment_gcm(121, 66) << std::endl;
  std::cout << "remainder(100, 7) = " << remainder(100, 7) << std::endl;
  std::cout << "quotient(100, 7) = " << quotient(100, 7) << std::endl;
  auto p = quotient_remainder(100, 7);
  std::cout << "quotient_remainder(100, 7) = pair<" << p.first << ", " << p.second << ">" << std::endl;
  std::cout << "remainder_fibonacci(100, 7) = " << remainder_fibonacci(100, 7) << std::endl;
  std::cout << "gcm_remainder(121, 66) = " << gcm_remainder(121, 66) << std::endl;
  std::cout << "gcd(121, 66) = " << gcd(121, 66) << std::endl;

}
Пример #12
0
Verylong operator/ (const Verylong &u, const Verylong &v)
{
	Verylong w,y,b,c,d,quotient("0");
             
	int len = u.vlen - v.vlen;
	
	if (v == Verylong("0"))
	{
		cerr << "Error: divide by zero" << endl;
		return Verylong("0");
	}

	w = abs(u); y = abs(v);
	if (w < y) return Verylong("0");
    
	char *temp = new char[w.vlen+1];
	strcpy(temp, w.vlstr + len);
	b.strrev(temp);
	c = Verylong(temp);
	delete [] temp;
	for (int i=0; i<=len; i++)
	{
		quotient = quotient.mult10(1);
		b = Verylong("0");
		d = Verylong("0");
		while (b < c)
		{	
            b = b + y; 
            d = d + Verylong("1"); 
        }
        
		if (c < b)
		{
			b = b - y;
			d = d - Verylong("1");
		}

		quotient+= d;

		if (i < len)
		{
			c = (c-b).mult10(1);
			c = c + Verylong(w.vlstr[len-i-1]-'0');
		}
	}

	quotient.vlsign = u.vlsign^v.vlsign;
	return quotient;
}
Пример #13
0
MyVector<double> DivideVectors(const MyVector<double>& numerator,
								const double& denominator) {
	//Make a new MyVector<double> of the same size as the divisors
	//Fill each element with zero

	const int vectorSize = numerator.Size();

	// Division for vectors which aren't the same size shouldn't take place
	MyVector<double> quotient(MV::Size(vectorSize), 0.);

	//Divide the vectors component-by-component
	for (int i=0; i < vectorSize; ++i) {
		quotient[i] = numerator[i] / denominator;
	}

	return quotient;
}
Пример #14
0
void doStuff(int x, int y) {
    try {
        if ( (x==13) || (y==13) ) {
            throw 13;
        }
        std::cout << "  " << x << " * " << y << " = " << shift(x,y) << std::endl;
        if ( (y == 0) ) {
            throw 0;
        }
        std::cout << "  " << x << " / " << y << " = " << quotient(x,y) << std::endl;
    }
    catch(int e) {
        if (e == 0)
            std::cout << "Warning: attempt to devide by 0!" << std::endl;
        else 
            std::cout << "Unlucky number !" << e << "!" << std::endl;
    }
}
Пример #15
0
CFX_PtrArray* CBC_ReedSolomonGF256Poly::Divide(CBC_ReedSolomonGF256Poly* other,
                                               int32_t& e) {
  if (other->IsZero()) {
    e = BCExceptionDivideByZero;
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  }
  CBC_ReedSolomonGF256Poly* rsg1 = m_field->GetZero()->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> quotient(rsg1);
  CBC_ReedSolomonGF256Poly* rsg2 = this->Clone(e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  CBC_AutoPtr<CBC_ReedSolomonGF256Poly> remainder(rsg2);
  int32_t denominatorLeadingTerm = other->GetCoefficients(other->GetDegree());
  int32_t inverseDenominatorLeadingTeam =
      m_field->Inverse(denominatorLeadingTerm, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
  while (remainder->GetDegree() >= other->GetDegree() && !remainder->IsZero()) {
    int32_t degreeDifference = remainder->GetDegree() - other->GetDegree();
    int32_t scale =
        m_field->Multiply(remainder->GetCoefficients((remainder->GetDegree())),
                          inverseDenominatorLeadingTeam);
    CBC_ReedSolomonGF256Poly* rsg3 =
        other->MultiplyByMonomial(degreeDifference, scale, e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> term(rsg3);
    CBC_ReedSolomonGF256Poly* rsg4 =
        m_field->BuildMonomial(degreeDifference, scale, e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> iteratorQuotient(rsg4);
    CBC_ReedSolomonGF256Poly* rsg5 =
        quotient->AddOrSubtract(iteratorQuotient.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp(rsg5);
    quotient = temp;
    CBC_ReedSolomonGF256Poly* rsg6 = remainder->AddOrSubtract(term.get(), e);
    BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
    CBC_AutoPtr<CBC_ReedSolomonGF256Poly> temp1(rsg6);
    remainder = temp1;
  }
  CFX_PtrArray* tempPtrA = new CFX_PtrArray;
  tempPtrA->Add(quotient.release());
  tempPtrA->Add(remainder.release());
  return tempPtrA;
}
      inline field_polynomial& field_polynomial::operator/=(const field_polynomial& divisor)
      {
         if (
             (field_        == divisor.field_) &&
             (deg()         >= divisor.deg())  &&
             (divisor.deg() >=             0)
            )
         {
            field_polynomial quotient(field_, deg() - divisor.deg() + 1);
            field_polynomial remainder(field_, divisor.deg() - 1);

            for (int i = static_cast<int>(deg()); i >= 0; i--)
            {
               if (i <= static_cast<int>(quotient.deg()))
               {
                  quotient[i] = remainder[remainder.deg()] / divisor[divisor.deg()];

                  for (int j = static_cast<int>(remainder.deg()); j > 0; --j)
                  {
                     remainder[j] = remainder[j - 1] + (quotient[i] * divisor[j]);
                  }

                  remainder[0] = poly_[i] + (quotient[i] * divisor[0]);
               }
               else
               {
                  for (int j = static_cast<int>(remainder.deg()); j > 0; --j)
                  {
                     remainder[j] = remainder[j - 1];
                  }

                  remainder[0] = poly_[i];
               }
            }

            simplify(quotient);
            poly_ = quotient.poly_;
         }

         return *this;
      }
Пример #17
0
void
ACE_Stats::mean (ACE_Stats_Value &m,
                 const ACE_UINT32 scale_factor)
{
  if (number_of_samples_ > 0)
    {
#if defined ACE_LACKS_LONGLONG_T
      // If ACE_LACKS_LONGLONG_T, then ACE_UINT64 is a user-defined class.
      // To prevent having to construct a static of that class, declare it
      // on the stack, and construct it, in each function that needs it.
      const ACE_U_LongLong ACE_STATS_INTERNAL_OFFSET (0, 8);
#else  /* ! ACE_LACKS_LONGLONG_T */
      const ACE_UINT64 ACE_STATS_INTERNAL_OFFSET =
        ACE_UINT64_LITERAL (0x100000000);
#endif /* ! ACE_LACKS_LONGLONG_T */

      ACE_UINT64 sum = ACE_STATS_INTERNAL_OFFSET;
      ACE_Unbounded_Queue_Iterator<ACE_INT32> i (samples_);
      while (! i.done ())
        {
          ACE_INT32 *sample;
          if (i.next (sample))
            {
              sum += *sample;
              i.advance ();
            }
        }

      // sum_ was initialized with ACE_STATS_INTERNAL_OFFSET, so
      // subtract that off here.
      quotient (sum - ACE_STATS_INTERNAL_OFFSET,
                number_of_samples_ * scale_factor,
                m);
    }
  else
    {
      m.whole (0);
      m.fractional (0);
    }
}
Пример #18
0
// celociselne deleni 2 dlouhych cisel (stredoskolsky algoritmus)
// -- viz http://courses.cs.vt.edu/~cs1104/BuildingBlocks/divide.030.html
LNum operator/(LNum & dividend, LNum & divisor) {
  LNum quotient(1);
  quotient[0] = 0;
  to_normal_form(dividend);
  to_normal_form(divisor);

  // deleni nulou !!
  if (divisor.get_size() == 1 && divisor[0] == 0) {
    cout << "Division by zero!! Returning \"0\"!" << endl;
    return quotient;
  }

  // deleni mensiho cisla vetsim -> podil == 0
  if (dividend < divisor) {
    LNum oh(1);
    return oh;
  }

  // zarovnej delitel do leveho rohu delence
  int lock = dividend.get_size() - divisor.get_size();  // zarazka zpracovavane
                                                        // cifry v dividendu
  LNum portion = cut(dividend, lock, dividend.get_size()-1);

  do {
    if (!(portion<divisor)) {
      portion = portion - divisor;
      quotient.append(1);
    } else {
      quotient.append(0);
    }
    if (--lock >= 0) {
      portion.append(dividend[lock]);
    }
  } while (lock >= 0);

  to_normal_form(quotient);

  return quotient;
}
Пример #19
0
void Write_Array(std::ostream& stream, const digit* array, size_t size, bool negative, size_t radix)
{
  if (negative)
    stream << minus_digit;
  
  Array_Buffer quotient(size), remainder(size), value(size);
  std::copy(array, array + size, value.data);
  
  if (Array_Zero(array, size)){
    stream << zero_digit;
    return;
  }

  digit factor = radix, factor_width = 1;
  while (true){
    uint64 temp = static_cast<uint64>(factor) * radix;
    if (temp >= digit_radix)
      break;
    factor = temp;
    ++factor_width;
  }

  std::vector<char> buffer;
  size_t width = 0;
  while (!Array_Zero(value.data, value.size)){
    Divide_Arrays(value.data, size, &factor, 1, quotient.data, size, remainder.data, size);
    Split_To_Digits(buffer, remainder.data[0], radix);
    width += factor_width;
    while (buffer.size() != width)
      buffer.push_back(zero_digit);
    std::copy(quotient.data, quotient.data + size, value.data);
  }

  size_t end = buffer.size();
  while (buffer[end - 1] == zero_digit)
    --end;
  for (size_t i = end; i != 0; --i)
    stream << buffer[i - 1];
}
Пример #20
0
CFX_ArrayTemplate<CBC_ReedSolomonGF256Poly*>* CBC_ReedSolomonGF256Poly::Divide(
    CBC_ReedSolomonGF256Poly* other,
    int32_t& e) {
  if (other->IsZero()) {
    e = BCExceptionDivideByZero;
    return nullptr;
  }
  std::unique_ptr<CBC_ReedSolomonGF256Poly> quotient(
      m_field->GetZero()->Clone(e));
  BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
  std::unique_ptr<CBC_ReedSolomonGF256Poly> remainder(Clone(e));
  BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
  int32_t denominatorLeadingTerm = other->GetCoefficients(other->GetDegree());
  int32_t inverseDenominatorLeadingTeam =
      m_field->Inverse(denominatorLeadingTerm, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
  while (remainder->GetDegree() >= other->GetDegree() && !remainder->IsZero()) {
    int32_t degreeDifference = remainder->GetDegree() - other->GetDegree();
    int32_t scale =
        m_field->Multiply(remainder->GetCoefficients((remainder->GetDegree())),
                          inverseDenominatorLeadingTeam);
    std::unique_ptr<CBC_ReedSolomonGF256Poly> term(
        other->MultiplyByMonomial(degreeDifference, scale, e));
    BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
    std::unique_ptr<CBC_ReedSolomonGF256Poly> iteratorQuotient(
        m_field->BuildMonomial(degreeDifference, scale, e));
    BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
    quotient.reset(quotient->AddOrSubtract(iteratorQuotient.get(), e));
    BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
    remainder.reset(remainder->AddOrSubtract(term.get(), e));
    BC_EXCEPTION_CHECK_ReturnValue(e, nullptr);
  }
  CFX_ArrayTemplate<CBC_ReedSolomonGF256Poly*>* tempPtrA =
      new CFX_ArrayTemplate<CBC_ReedSolomonGF256Poly*>();
  tempPtrA->Add(quotient.release());
  tempPtrA->Add(remainder.release());
  return tempPtrA;
}
Пример #21
0
Figure 13.9  Conditional Compilation of Tracing printf Calls
/*
 *  Computes an integer quotient (m/n) using subtraction
 */
int
quotient(int m, int n)
{
      int ans;
#if defined (TRACE)
      printf("Entering quotient with m = %d, n = %d\n", 
m, n);
#endif

      if (n > m)
            ans = 0;
      else
            ans = 1 + quotient(m - n, n);

#if defined (TRACE)
      printf("Leaving quotient(%d, %d) with result = %d\n", m, n, ans);
#endif

      return (ans);
}
Пример #22
0
int quotient (int m, int n)
{
	int ans;

#if defined (TRACE_VERBOSE)
	printf ("Entering quotient with %d and %d\n", m, n);
#elif defined (TRACE_BRIEF)
	printf (" => quotient (%d, %d)\n", m, n);
#endif

	if (n > m) {
		ans = 0;
	} else {
		ans = 1 + quotient (m-n, n);
	}

#if defined (TRACE_VERBOSE)
	printf("Leaving quotient(%d, %d) with result = %d\n", m, n, ans);
#elif defined (TRACE_BRIEF)
	printf("quotient(%d, %d) => %d\n", m, n, ans);
#endif

	return (ans);
}
Пример #23
0
int
ACE_Stats::print_summary (const u_int precision,
                          const ACE_UINT32 scale_factor,
                          FILE *file) const
{
  ACE_TCHAR mean_string [128];
  ACE_TCHAR std_dev_string [128];
  ACE_TCHAR min_string [128];
  ACE_TCHAR max_string [128];
  int success = 0;

  for (int tmp_precision = precision;
       ! overflow_  &&  ! success  &&  tmp_precision >= 0;
       --tmp_precision)
    {
      // Build a format string, in case the C library doesn't support %*u.
      ACE_TCHAR format[32];
      if (tmp_precision == 0)
        ACE_OS::snprintf (format, 32, ACE_TEXT ("%%%d"), tmp_precision);
      else
        ACE_OS::snprintf (format, 32, ACE_TEXT ("%%d.%%0%du"), tmp_precision);

      ACE_Stats_Value u (tmp_precision);
      ((ACE_Stats *) this)->mean (u, scale_factor);
      ACE_OS::snprintf (mean_string, 128, format, u.whole (), u.fractional ());

      ACE_Stats_Value sd (tmp_precision);
      if (((ACE_Stats *) this)->std_dev (sd, scale_factor))
        {
          success = 0;
          continue;
        }
      else
        {
          success = 1;
        }
      ACE_OS::snprintf (std_dev_string, 128, format, sd.whole (),
                        sd.fractional ());

      ACE_Stats_Value minimum (tmp_precision), maximum (tmp_precision);
      if (min_ != 0)
        {
          const ACE_UINT64 m (min_);
          quotient (m, scale_factor, minimum);
        }
      if (max_ != 0)
        {
          const ACE_UINT64 m (max_);
          quotient (m, scale_factor, maximum);
        }
      ACE_OS::snprintf (min_string, 128, format,
                        minimum.whole (), minimum.fractional ());
      ACE_OS::snprintf (max_string, 128, format,
                        maximum.whole (), maximum.fractional ());
    }

  if (success == 1)
    {
      ACE_OS::fprintf (file, ACE_TEXT ("samples: %u (%s - %s); mean: ")
                       ACE_TEXT ("%s; std dev: %s\n"),
                       samples (), min_string, max_string,
                       mean_string, std_dev_string);
      return 0;
    }
  else
    {
      ACE_OS::fprintf (file,
                       ACE_TEXT ("ACE_Stats::print_summary: OVERFLOW: %s\n"),
                       ACE_OS::strerror (overflow_));

      return -1;
    }
}
Пример #24
0
bigint* simp_worbitsize(entry* w, simpgrp* g)
 /* |w| is assumed to be dominant */
{ return quotient(simp_worder(copybigint(one,NULL),g),simp_stabsize(w,g)); }
Пример #25
0
/* 정수형 나눗셈의 계산 및 결과 출력 */
static void
int_divide (int n1, int n2)
{
  printf ("%d / %d의 몫 : %d \n", n1, n2, quotient (n1, n2));
  printf ("%d / %d의 나머지 : %d \n", n1, n2, re_mainder (n1, n2));
}
    void Evaluator::multiply(const uint64_t *encrypted1, const uint64_t *encrypted2, uint64_t *destination)
    {
        // Extract encryption parameters.
        int coeff_count = poly_modulus_.coeff_count();
        int coeff_bit_count = poly_modulus_.coeff_bit_count();
        int coeff_uint64_count = divide_round_up(coeff_bit_count, bits_per_uint64);

        // Clear destatintion.
        set_zero_poly(coeff_count, coeff_uint64_count, destination);

        // Determine if FFT can be used.
        bool use_fft = polymod_.coeff_count_power_of_two() >= 0 && polymod_.is_one_zero_one();

        if (use_fft)
        {
            // Use FFT to multiply polynomials.

            // Allocate polynomial to store product of two polynomials, with poly but no coeff modulo yet (and signed).
            int product_coeff_bit_count = coeff_bit_count + coeff_bit_count + get_significant_bit_count(static_cast<uint64_t>(coeff_count)) + 2;
            int product_coeff_uint64_count = divide_round_up(product_coeff_bit_count, bits_per_uint64);
            Pointer product(allocate_poly(coeff_count, product_coeff_uint64_count, pool_));

            // Use FFT to multiply polynomials.
            set_zero_uint(product_coeff_uint64_count, get_poly_coeff(product.get(), coeff_count - 1, product_coeff_uint64_count));
            fftmultiply_poly_poly_polymod(encrypted1, encrypted2, polymod_.coeff_count_power_of_two(), coeff_uint64_count, product_coeff_uint64_count, product.get(), pool_);

            // For each coefficient in product, multiply by plain_modulus and divide by coeff_modulus and then modulo by coeff_modulus.
            int plain_modulus_bit_count = plain_modulus_.significant_bit_count();
            int plain_modulus_uint64_count = divide_round_up(plain_modulus_bit_count, bits_per_uint64);
            int intermediate_bit_count = product_coeff_bit_count + plain_modulus_bit_count - 1;
            int intermediate_uint64_count = divide_round_up(intermediate_bit_count, bits_per_uint64);
            Pointer intermediate(allocate_uint(intermediate_uint64_count, pool_));
            Pointer quotient(allocate_uint(intermediate_uint64_count, pool_));
            for (int coeff_index = 0; coeff_index < coeff_count; ++coeff_index)
            {
                uint64_t *product_coeff = get_poly_coeff(product.get(), coeff_index, product_coeff_uint64_count);
                bool coeff_is_negative = is_high_bit_set_uint(product_coeff, product_coeff_uint64_count);
                if (coeff_is_negative)
                {
                    negate_uint(product_coeff, product_coeff_uint64_count, product_coeff);
                }
                multiply_uint_uint(product_coeff, product_coeff_uint64_count, plain_modulus_.pointer(), plain_modulus_uint64_count, intermediate_uint64_count, intermediate.get());
                add_uint_uint(intermediate.get(), wide_coeff_modulus_div_two_.pointer(), intermediate_uint64_count, intermediate.get());
                divide_uint_uint_inplace(intermediate.get(), wide_coeff_modulus_.pointer(), intermediate_uint64_count, quotient.get(), pool_);
                modulo_uint_inplace(quotient.get(), intermediate_uint64_count, mod_, pool_);
                uint64_t *dest_coeff = get_poly_coeff(destination, coeff_index, coeff_uint64_count);
                if (coeff_is_negative)
                {
                    negate_uint_mod(quotient.get(), coeff_modulus_.pointer(), coeff_uint64_count, dest_coeff);
                }
                else
                {
                    set_uint_uint(quotient.get(), coeff_uint64_count, dest_coeff);
                }
            }
        }
        else
        {
            // Use normal multiplication to multiply polynomials.

            // Allocate polynomial to store product of two polynomials, with no poly or coeff modulo yet.
            int product_coeff_count = coeff_count + coeff_count - 1;
            int product_coeff_bit_count = coeff_bit_count + coeff_bit_count + get_significant_bit_count(static_cast<uint64_t>(coeff_count));
            int product_coeff_uint64_count = divide_round_up(product_coeff_bit_count, bits_per_uint64);
            Pointer product(allocate_poly(product_coeff_count, product_coeff_uint64_count, pool_));

            // Multiply polynomials.
            multiply_poly_poly(encrypted1, coeff_count, coeff_uint64_count, encrypted2, coeff_count, coeff_uint64_count, product_coeff_count, product_coeff_uint64_count, product.get(), pool_);

            // For each coefficient in product, multiply by plain_modulus and divide by coeff_modulus and then modulo by coeff_modulus.
            int plain_modulus_bit_count = plain_modulus_.significant_bit_count();
            int plain_modulus_uint64_count = divide_round_up(plain_modulus_bit_count, bits_per_uint64);
            int intermediate_bit_count = product_coeff_bit_count + plain_modulus_bit_count;
            int intermediate_uint64_count = divide_round_up(intermediate_bit_count, bits_per_uint64);
            Pointer intermediate(allocate_uint(intermediate_uint64_count, pool_));
            Pointer quotient(allocate_uint(intermediate_uint64_count, pool_));
            Pointer productmoded(allocate_poly(product_coeff_count, coeff_uint64_count, pool_));
            for (int coeff_index = 0; coeff_index < product_coeff_count; ++coeff_index)
            {
                const uint64_t *product_coeff = get_poly_coeff(product.get(), coeff_index, product_coeff_uint64_count);
                multiply_uint_uint(product_coeff, product_coeff_uint64_count, plain_modulus_.pointer(), plain_modulus_uint64_count, intermediate_uint64_count, intermediate.get());
                add_uint_uint(intermediate.get(), wide_coeff_modulus_div_two_.pointer(), intermediate_uint64_count, intermediate.get());
                divide_uint_uint_inplace(intermediate.get(), wide_coeff_modulus_.pointer(), intermediate_uint64_count, quotient.get(), pool_);
                modulo_uint_inplace(quotient.get(), intermediate_uint64_count, mod_, pool_);
                uint64_t *productmoded_coeff = get_poly_coeff(productmoded.get(), coeff_index, coeff_uint64_count);
                set_uint_uint(quotient.get(), coeff_uint64_count, productmoded_coeff);
            }

            // Perform polynomial modulo.
            modulo_poly_inplace(productmoded.get(), product_coeff_count, polymod_, mod_, pool_);

            // Copy to destination.
            set_poly_poly(productmoded.get(), coeff_count, coeff_uint64_count, destination);
        }
    }
Пример #27
0
int
ACE_Stats::std_dev (ACE_Stats_Value &std_dev,
                    const ACE_UINT32 scale_factor)
{
  if (number_of_samples_ <= 1)
    {
      std_dev.whole (0);
      std_dev.fractional (0);
    }
  else
    {
      const ACE_UINT32 field = std_dev.fractional_field ();

      // The sample standard deviation is:
      //
      // sqrt (sum (sample_i - mean)^2 / (number_of_samples_ - 1))

      ACE_UINT64 mean_scaled;
      // Calculate the mean, scaled, so that we don't lose its
      // precision.
      ACE_Stats_Value avg (std_dev.precision ());
      mean (avg, 1u);
      avg.scaled_value (mean_scaled);

      // Calculate the summation term, of squared differences from the
      // mean.
      ACE_UINT64 sum_of_squares = 0;
      ACE_Unbounded_Queue_Iterator<ACE_INT32> i (samples_);
      while (! i.done ())
        {
          ACE_INT32 *sample;
          if (i.next (sample))
            {
              const ACE_UINT64 original_sum_of_squares = sum_of_squares;

              // Scale up by field width so that we don't lose the
              // precision of the mean.  Carefully . . .
              const ACE_UINT64 product (*sample * field);

              ACE_UINT64 difference;
              // NOTE: please do not reformat this code!  It //
              // works with the Diab compiler the way it is! //
              if  (product >= mean_scaled)                   //
                {                                            //
                  difference = product - mean_scaled;        //
                }                                            //
              else                                           //
                {                                            //
                  difference = mean_scaled - product;        //
                }                                            //
              // NOTE: please do not reformat this code!  It //
              // works with the Diab compiler the way it is! //

              // Square using 64-bit arithmetic.
              sum_of_squares += difference * ACE_U64_TO_U32 (difference);
              i.advance ();

              if (sum_of_squares < original_sum_of_squares)
                {
                  overflow_ = ENOSPC;
                  return -1;
                }
            }
        }

      // Divide the summation by (number_of_samples_ - 1), to get the
      // variance.  In addition, scale the variance down to undo the
      // mean scaling above.  Otherwise, it can get too big.
      ACE_Stats_Value variance (std_dev.precision ());
      quotient (sum_of_squares,
                (number_of_samples_ - 1) * field * field,
                variance);

      // Take the square root of the variance to get the standard
      // deviation.  First, scale up . . .
      ACE_UINT64 scaled_variance;
      variance.scaled_value (scaled_variance);

      // And scale up, once more, because we'll be taking the square
      // root.
      scaled_variance *= field;
      ACE_Stats_Value unscaled_standard_deviation (std_dev.precision ());
      square_root (scaled_variance,
                   unscaled_standard_deviation);

      // Unscale.
      quotient (unscaled_standard_deviation,
                scale_factor * field,
                std_dev);
    }

  return 0;
}
SExp* Eval::apply(SExp* f, SExp* x, SExp* a,Tree* d)
{
	char sStr[1000];

	memset(sStr,0,1000);

	if(f->isAtom==0)
	{
		f->convertString(sStr);
		ErrorManager E;
		E.buildRunTimeErrors(ErrorManager::NON_ATOMIC_FUNC,sStr);
	}

	if(f->value[0]=='\0')
	{
		f->convertString(sStr);
		ErrorManager E;
		E.buildRunTimeErrors(ErrorManager::F_VALUE_NULL,sStr);
	}

	if(strcmp(f->value,"NULL")==0)
	{
		if(x->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return isNull(x->car);
	}

	if(strcmp(f->value,"ATOM")==0)
	{
		if(x->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return atom(x->car);
	}

	if(strcmp(f->value,"INT")==0)
	{
		if(x->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return Int(x->car);
	}

	if(strcmp(f->value,"CAR")==0)
	{
		if(x->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return car(x->car);
	}

	if(strcmp(f->value,"CDR")==0)
	{
		if(x->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return cdr(x->car);
	}

	if(strcmp(f->value,"EQ")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);

		}
		else
			return eq(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"CONS")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return cons(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"PLUS")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return plus(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"MINUS")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return minus(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"TIMES")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return times(x->car,x->cdr->car);
	}


	if(strcmp(f->value,"QUOTIENT")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return quotient(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"REMAINDER")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);

		}
		else
			return remainder(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"GREATER")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return greater(x->car,x->cdr->car);
	}

	if(strcmp(f->value,"LESS")==0)
	{
		if(x->car==NULL || x->cdr->car==NULL)
		{
			x->convertString(sStr);
			ErrorManager E;
			E.buildRunTimeErrors(ErrorManager::ARGUMENT_NO_MATCH,sStr);
		}
		else
			return less(x->car,x->cdr->car);
	}

	SExp* body = getFunc(f, d)->cdr;
	if(body!=NULL){}
	else
		return NULL;

	SExp* SE = addPairs(getFunc(f, d)->car, x, a);
	if(SE!=NULL){

	}else
		return NULL;

	return eval(body,SE,d);
}
Пример #29
0
void my_exceptions::run()
{   
    cout << "BBeguTe 4epe3 npo6eL gBa 4ucLa gLq geLeHuq:\n";
    cin >> num1 >> num2;  
    quotient();
}