예제 #1
0
        public static object SqrtBigInteger(object num)
        {
            BigInteger x = (BigInteger)num;
            BigInteger v0, q0, x1;

            if (x <= 1)
            {
                return(x);
            }

            v0 = x;
            x  = x / 2;
            while (true)
            {
                q0 = v0 / x;
                x1 = (x + q0) / 2;
                if (q0 >= x)
                {
                    break;
                }
                x = x1;
            }
            if (x1 * x1 != v0)
            {
                return(Math.Sqrt(v0.ToFloat64()));
            }
            return(x1);
        }
예제 #2
0
        public static bool GetComponents(this double d, out BigInteger numerator, out BigInteger denominator)
        {
            if (double.IsNaN(d))
            {
                numerator = denominator = 0;
                return(false);
            }

            if (double.IsNegativeInfinity(d))
            {
                numerator   = -1;
                denominator = 0;
                return(false);
            }

            if (double.IsPositiveInfinity(d))
            {
                numerator   = 1;
                denominator = 0;
                return(false);
            }

            if (d == 0.0)
            {
                numerator   = 0;
                denominator = 1;
                return(true);
            }

            var r = BitConverter.DoubleToInt64Bits(d);

            var m = GetMantissa(r);
            var e = GetExponent(r);
            var s = GetSign(r) == 0 ? 1 : -1;

            const int BIAS = 1023;
            var       re   = e - BIAS;

            var exp = (((BigInteger)1) << Math.Abs(re));

            if (e == 0)
            {
                denominator = s * exp * (MANTISSA >> 1);
                numerator   = m;
                return(true);
            }

            if (re < 0)
            {
                denominator = MANTISSA * s * exp;
                numerator   = (MANTISSA + m);
            }
            else
            {
                denominator = MANTISSA * s;
                numerator   = exp * (MANTISSA + m);
            }

            return(true);
        }
예제 #3
0
        public static bool GetMantissaAndExponent(this double d, out BigInteger mantissa, out BigInteger exponent)
        {
            if (double.IsNaN(d))
            {
                mantissa = exponent = 0;
                return(false);
            }

            if (double.IsNegativeInfinity(d))
            {
                mantissa = -1;
                exponent = 0;
                return(false);
            }

            if (double.IsPositiveInfinity(d))
            {
                mantissa = 1;
                exponent = 0;
                return(false);
            }

            var r = BitConverter.DoubleToInt64Bits(d);

            var man = GetMantissa(r);
            var exp = GetExponent(r);

            const int BIAS = 1075;

            exponent = exp - BIAS;
            mantissa = man + MANTISSA;

            return(true);
        }
예제 #4
0
        public static object ExactSqrtBigInteger(object num)
        {
            BigInteger x = (BigInteger)num;
            BigInteger v0, q0, x1;

            if (x <= 1)
            {
                return(x);
            }

            v0 = x;
            x  = x / 2;
            while (true)
            {
                q0 = v0 / x;
                x1 = (x + q0) / 2;
                if (q0 >= x)
                {
                    break;
                }
                x = x1;
            }
            q0 = x1 * x1;

            if (q0 > v0)
            {
                x1 = x1 - 1;
                q0 = x1 * x1;
            }
            return(Values(ToIntegerIfPossible(x1), ToIntegerIfPossible(v0 - q0)));
        }
예제 #5
0
        /// <summary>
        /// The classic GCD algorithm of Euclid
        /// </summary>
        /// <param name="smaller"></param>
        /// <param name="larger"></param>
        /// <returns></returns>
        internal BigInteger Gcd(BigInteger smaller, BigInteger larger)
        {
            BigInteger rest;

            smaller = smaller.Abs();
            larger  = larger.Abs();

            if (smaller == 0)
            {
                return(larger);
            }
            else
            {
                if (larger == 0)
                {
                    return(smaller);
                }
            }


            // the GCD algorithm requires second >= first
            if (smaller > larger)
            {
                rest    = larger;
                larger  = smaller;
                smaller = rest;
            }

            while ((rest = larger % smaller) != 0)
            {
                larger  = smaller;
                smaller = rest;
            }
            return(smaller);
        }
예제 #6
0
    public static bool GetMantissaAndExponent(this double d, out BigInteger mantissa, out BigInteger exponent)
    {
      if (double.IsNaN(d))
      {
        mantissa = exponent = 0;
        return false;
      }

      if (double.IsNegativeInfinity(d))
      {
        mantissa = -1;
        exponent = 0;
        return false;
      }

      if (double.IsPositiveInfinity(d))
      {
        mantissa = 1;
        exponent = 0;
        return false;
      }

      var r = BitConverter.DoubleToInt64Bits(d);

      var man = GetMantissa(r);
      var exp = GetExponent(r);

      const int BIAS = 1075;
      exponent = exp - BIAS;
      mantissa = man + MANTISSA;

      return true;
    }
예제 #7
0
 static object Expt10(int tnum)
 {
     if (tnum < 0)
     {
         return(new Fraction(1, BigInteger.Pow(10, (uint)-tnum)));
     }
     return(BigInteger.Pow(TEN, (uint)tnum));
 }
예제 #8
0
        public static Fraction operator %(Fraction fraction1, Fraction fraction2)
        {
            BigInteger quo = (BigInteger)(fraction1 / fraction2);

            return(fraction1 - new Fraction(
                       fraction2.numerator * quo,
                       fraction2.denominator));
        }
예제 #9
0
        /// <summary>
        /// Parse a sequence of digits into a BigInteger.
        /// </summary>
        /// <param name="data">The DecimalFloatingPointString containing the digits in its Mantissa</param>
        /// <param name="integer_first_index">The index of the first digit to convert</param>
        /// <param name="integer_last_index">The index just past the last digit to convert</param>
        /// <returns>The BigInteger result</returns>
        private static BigInteger AccumulateDecimalDigitsIntoBigInteger(DecimalFloatingPointString data, uint integer_first_index, uint integer_last_index)
        {
            if (integer_first_index == integer_last_index)
            {
                return(BigZero);
            }
            var valueString = data.Mantissa.Substring((int)integer_first_index, (int)(integer_last_index - integer_first_index));

            return(BigInteger.Parse(valueString.TrimStart('0'))); // our bigint does octals too
        }
예제 #10
0
 protected internal static object ToIntegerIfPossible(BigInteger i)
 {
     if (i.IsInt32)
     {
         return(RuntimeHelpers.Int32ToObject((int)i));
     }
     else
     {
         return(i);
     }
 }
예제 #11
0
 // improve this
 protected internal static object ToIntegerIfPossible(BigInteger i)
 {
     if (i <= int.MaxValue && i >= int.MinValue)
     {
         return(RuntimeHelpers.Int32ToObject((int)i));
     }
     else
     {
         return(i);
     }
 }
예제 #12
0
    static void Main(string[] args)
    {
        string strFromIP = "192.168.0.1";
        string strToIP   = "192.168.255.255";

        IsValidIP(strFromIP, ref _omiFromIP);
        IsValidIP(strToIP, ref _omiToIP);
        for (_omiCurrentIp = _omiFromIP; _omiCurrentIp <= _omiFromIP + InitalRequests; ++_omiCurrentIp)
        {
            Console.WriteLine(IPn2IPv4(_omiCurrentIp));
            System.Net.IPAddress sniIPaddress = System.Net.IPAddress.Parse(IPn2IPv4(_omiCurrentIp));
            SendPingAsync(sniIPaddress);
        }
        Console.WriteLine(" --- Press any key to continue --- ");
        Console.ReadKey();
    }     // Main
예제 #13
0
        /// <summary>
        /// The classic GCD algorithm of Euclid
        /// </summary>
        /// <param name="smaller"></param>
        /// <param name="larger"></param>
        /// <returns></returns>
        internal BigInteger Gcd(BigInteger smaller, BigInteger larger)
        {
            if (smaller.IsInt && larger.IsInt)
            {
                return(Gcd((uint)smaller, (uint)larger));
            }

            if (smaller.IsLong && larger.IsLong)
            {
                return(Gcd((ulong)smaller, (ulong)larger));
            }

            BigInteger rest;

            smaller = smaller.Abs();
            larger  = larger.Abs();

            if (smaller == 0)
            {
                return(larger);
            }
            else
            {
                if (larger == 0)
                {
                    return(smaller);
                }
            }

            // the GCD algorithm requires second >= first
            if (smaller > larger)
            {
                rest    = larger;
                larger  = smaller;
                smaller = rest;
            }

            while ((rest = larger % smaller) != 0)
            {
                larger  = smaller;
                smaller = rest;
            }
            return(smaller);
        }
예제 #14
0
        /// <summary>
        /// Return the number of significant bits set.
        /// </summary>
        private static uint CountSignificantBits(BigInteger data, out byte[] dataBytes)
        {
            if (data == BigZero)
            {
                dataBytes = new byte[1];
                return(0);
            }

            dataBytes = data.ToByteArray(); // the bits of the BigInteger, least significant bits first
            for (int i = dataBytes.Length - 1; i >= 0; i--)
            {
                var v = dataBytes[i];
                if (v != 0)
                {
                    return(8 * (uint)i + CountSignificantBits(v));
                }
            }

            return(0);
        }
예제 #15
0
        public Fraction(BigInteger newNumerator, BigInteger newDenominator)
        {
            BigInteger gcd;

            if (newDenominator == 0)
            {
                throw new DivideByZeroException("Illegal fraction");
            }

            numerator   = newNumerator;
            denominator = newDenominator;
            if (denominator < 0)
            {
                numerator   *= -1;
                denominator *= -1;
            }

            gcd          = this.Gcd(numerator, denominator);
            numerator   /= gcd;
            denominator /= gcd;
        }
예제 #16
0
 /// <summary>
 /// Return the number of significant bits set.
 /// </summary>
 private static uint CountSignificantBits(BigInteger data)
 {
     byte[] dataBytes;
     return(CountSignificantBits(data, out dataBytes));
 }
예제 #17
0
 /// <summary>
 /// Return the number of significant bits set. 
 /// </summary>
 private static uint CountSignificantBits(BigInteger data)
 {
     byte[] dataBytes;
     return CountSignificantBits(data, out dataBytes);
 }
예제 #18
0
        /// <summary>
        /// Convert a DecimalFloatingPointString to the bits of the given floating-point type.
        /// </summary>
        private static SLD_STATUS ConvertDecimalToFloatingPointBits(DecimalFloatingPointString data, FloatingPointType type, out ulong result)
        {
            if (data.Mantissa.Length == 0)
            {
                result = type.Zero;
                return(SLD_STATUS.SLD_NODIGITS);
            }

            // To generate an N bit mantissa we require N + 1 bits of precision.  The
            // extra bit is used to correctly round the mantissa (if there are fewer bits
            // than this available, then that's totally okay; in that case we use what we
            // have and we don't need to round).
            uint requiredBitsOfPrecision = (uint)type.NormalMantissaBits + 1;

            // The input is of the form 0.Mantissa x 10^Exponent, where 'Mantissa' are
            // the decimal digits of the mantissa and 'Exponent' is the decimal exponent.
            // We decompose the mantissa into two parts: an integer part and a fractional
            // part.  If the exponent is positive, then the integer part consists of the
            // first 'exponent' digits, or all present digits if there are fewer digits.
            // If the exponent is zero or negative, then the integer part is empty.  In
            // either case, the remaining digits form the fractional part of the mantissa.
            uint positiveExponent     = (uint)Math.Max(0, data.Exponent);
            uint integerDigitsPresent = Math.Min(positiveExponent, data.MantissaCount);
            uint integerDigitsMissing = positiveExponent - integerDigitsPresent;
            uint integerFirstIndex    = 0;
            uint integerLastIndex     = integerDigitsPresent;

            uint fractionalFirstIndex    = integerLastIndex;
            uint fractionalLastIndex     = data.MantissaCount;
            uint fractionalDigitsPresent = fractionalLastIndex - fractionalFirstIndex;

            // First, we accumulate the integer part of the mantissa into a big_integer:
            BigInteger integerValue = AccumulateDecimalDigitsIntoBigInteger(data, integerFirstIndex, integerLastIndex);

            if (integerDigitsMissing > 0)
            {
                if (integerDigitsMissing > type.OverflowDecimalExponent)
                {
                    result = type.Infinity;
                    return(SLD_STATUS.SLD_OVERFLOW);
                }

                MultiplyByPowerOfTen(ref integerValue, integerDigitsMissing);
            }

            // At this point, the integer_value contains the value of the integer part
            // of the mantissa.  If either [1] this number has more than the required
            // number of bits of precision or [2] the mantissa has no fractional part,
            // then we can assemble the result immediately:
            byte[] integerValueAsBytes;
            uint   integerBitsOfPrecision = CountSignificantBits(integerValue, out integerValueAsBytes);

            if (integerBitsOfPrecision >= requiredBitsOfPrecision ||
                fractionalDigitsPresent == 0)
            {
                return(ConvertBigIntegerToFloatingPointBits(
                           integerValueAsBytes,
                           integerBitsOfPrecision,
                           fractionalDigitsPresent != 0,
                           type,
                           out result));
            }

            // Otherwise, we did not get enough bits of precision from the integer part,
            // and the mantissa has a fractional part.  We parse the fractional part of
            // the mantsisa to obtain more bits of precision.  To do this, we convert
            // the fractional part into an actual fraction N/M, where the numerator N is
            // computed from the digits of the fractional part, and the denominator M is
            // computed as the power of 10 such that N/M is equal to the value of the
            // fractional part of the mantissa.

            uint fractionalDenominatorExponent = data.Exponent < 0
                ? fractionalDigitsPresent + (uint)-data.Exponent
                : fractionalDigitsPresent;

            if (integerBitsOfPrecision == 0 && (fractionalDenominatorExponent - (int)data.MantissaCount) > type.OverflowDecimalExponent)
            {
                // If there were any digits in the integer part, it is impossible to
                // underflow (because the exponent cannot possibly be small enough),
                // so if we underflow here it is a true underflow and we return zero.
                result = type.Zero;
                return(SLD_STATUS.SLD_UNDERFLOW);
            }

            BigInteger fractionalNumerator = AccumulateDecimalDigitsIntoBigInteger(data, fractionalFirstIndex, fractionalLastIndex);
            //Debug.Assert(!fractionalNumerator.IsZero);

            BigInteger fractionalDenominator = BigOne;

            MultiplyByPowerOfTen(ref fractionalDenominator, fractionalDenominatorExponent);

            // Because we are using only the fractional part of the mantissa here, the
            // numerator is guaranteed to be smaller than the denominator.  We normalize
            // the fraction such that the most significant bit of the numerator is in
            // the same position as the most significant bit in the denominator.  This
            // ensures that when we later shift the numerator N bits to the left, we
            // will produce N bits of precision.
            uint fractionalNumeratorBits   = CountSignificantBits(fractionalNumerator);
            uint fractionalDenominatorBits = CountSignificantBits(fractionalDenominator);

            uint fractionalShift = fractionalDenominatorBits > fractionalNumeratorBits
                ? fractionalDenominatorBits - fractionalNumeratorBits
                : 0;

            if (fractionalShift > 0)
            {
                ShiftLeft(ref fractionalNumerator, fractionalShift);
            }

            uint requiredFractionalBitsOfPrecision =
                requiredBitsOfPrecision -
                integerBitsOfPrecision;

            uint remainingBitsOfPrecisionRequired = requiredFractionalBitsOfPrecision;

            if (integerBitsOfPrecision > 0)
            {
                // If the fractional part of the mantissa provides no bits of precision
                // and cannot affect rounding, we can just take whatever bits we got from
                // the integer part of the mantissa.  This is the case for numbers like
                // 5.0000000000000000000001, where the significant digits of the fractional
                // part start so far to the right that they do not affect the floating
                // point representation.
                //
                // If the fractional shift is exactly equal to the number of bits of
                // precision that we require, then no fractional bits will be part of the
                // result, but the result may affect rounding.  This is e.g. the case for
                // large, odd integers with a fractional part greater than or equal to .5.
                // Thus, we need to do the division to correctly round the result.
                if (fractionalShift > remainingBitsOfPrecisionRequired)
                {
                    return(ConvertBigIntegerToFloatingPointBits(
                               integerValueAsBytes,
                               integerBitsOfPrecision,
                               fractionalDigitsPresent != 0,
                               type,
                               out result));
                }

                remainingBitsOfPrecisionRequired -= fractionalShift;
            }

            // If there was no integer part of the mantissa, we will need to compute the
            // exponent from the fractional part.  The fractional exponent is the power
            // of two by which we must multiply the fractional part to move it into the
            // range [1.0, 2.0).  This will either be the same as the shift we computed
            // earlier, or one greater than that shift:
            uint fractionalExponent = fractionalNumerator < fractionalDenominator
                ? fractionalShift + 1
                : fractionalShift;

            ShiftLeft(ref fractionalNumerator, remainingBitsOfPrecisionRequired);
            BigInteger fractionalRemainder;
            BigInteger bigFractionalMantissa = BigInteger.DivideModulo(fractionalNumerator, fractionalDenominator, out fractionalRemainder);
            ulong      fractionalMantissa    = (ulong)bigFractionalMantissa;

            bool hasZeroTail = fractionalRemainder == BigZero;

            // We may have produced more bits of precision than were required.  Check,
            // and remove any "extra" bits:
            uint fractionalMantissaBits = CountSignificantBits(fractionalMantissa);

            if (fractionalMantissaBits > requiredFractionalBitsOfPrecision)
            {
                int shift = (int)(fractionalMantissaBits - requiredFractionalBitsOfPrecision);
                hasZeroTail          = hasZeroTail && (fractionalMantissa & ((1UL << shift) - 1)) == 0;
                fractionalMantissa >>= shift;
            }

            // Compose the mantissa from the integer and fractional parts:
            Debug.Assert(integerBitsOfPrecision < 60); // we can use BigInteger's built-in conversion
            ulong integerMantissa = (ulong)integerValue;

            ulong completeMantissa =
                (integerMantissa << (int)requiredFractionalBitsOfPrecision) +
                fractionalMantissa;

            // Compute the final exponent:
            // * If the mantissa had an integer part, then the exponent is one less than
            //   the number of bits we obtained from the integer part.  (It's one less
            //   because we are converting to the form 1.11111, with one 1 to the left
            //   of the decimal point.)
            // * If the mantissa had no integer part, then the exponent is the fractional
            //   exponent that we computed.
            // Then, in both cases, we subtract an additional one from the exponent, to
            // account for the fact that we've generated an extra bit of precision, for
            // use in rounding.
            int finalExponent = integerBitsOfPrecision > 0
                ? (int)integerBitsOfPrecision - 2
                : -(int)(fractionalExponent) - 1;

            return(type.AssembleFloatingPointValue(completeMantissa, finalExponent, hasZeroTail, out result));
        }
예제 #19
0
 /// <summary>
 /// Multiply a BigInteger by the given power of ten.
 /// </summary>
 /// <param name="number">The BigInteger to multiply by a power of ten and replace with the product</param>
 /// <param name="power">The power of ten to multiply it by</param>
 private static void MultiplyByPowerOfTen(ref BigInteger number, uint power)
 {
     var powerOfTen = BigInteger.Pow(BigTen, power);
     number = number * powerOfTen;
 }
예제 #20
0
		public Fraction(BigInteger newNumerator, BigInteger newDenominator)
		{
			BigInteger gcd;

			if (newDenominator == 0)
				throw new DivideByZeroException("Illegal fraction");

			numerator = newNumerator;
			denominator = newDenominator;
			if (denominator < 0)
			{
				numerator *= -1;
				denominator *= -1;
			}

			gcd = this.Gcd(numerator, denominator);
			numerator /= gcd;
			denominator /= gcd;
		}
예제 #21
0
 /// <summary>
 /// Multiply a BigInteger by the given power of two.
 /// </summary>
 /// <param name="number">The BigInteger to multiply by a power of two and replace with the product</param>
 /// <param name="shift">The power of two to multiply it by</param>
 private static void ShiftLeft(ref BigInteger number, uint shift)
 {
     var powerOfTwo = BigInteger.Pow(BigTwo, shift);
     number = number * powerOfTwo;
 }
예제 #22
0
 // improve this
 protected internal static object ToIntegerIfPossible(BigInteger i)
 {
     if (i <= int.MaxValue && i >= int.MinValue)
       {
     return RuntimeHelpers.Int32ToObject((int)i);
       }
       else
       {
     return i;
       }
 }
예제 #23
0
        /// <summary>
        /// Return the number of significant bits set. 
        /// </summary>
        private static uint CountSignificantBits(BigInteger data, out byte[] dataBytes)
        {
            if (data == BigZero)
            {
                dataBytes = new byte[1];
                return 0;
            }

            dataBytes = data.ToByteArray(); // the bits of the BigInteger, least significant bits first
            for (int i = dataBytes.Length - 1; i >= 0; i--)
            {
                var v = dataBytes[i];
                if (v != 0) return 8 * (uint)i + CountSignificantBits(v);
            }

            return 0;
        }
예제 #24
0
		/// <summary>
		/// The classic GCD algorithm of Euclid
		/// </summary>
    /// <param name="smaller"></param>
    /// <param name="larger"></param>
		/// <returns></returns>
		internal BigInteger Gcd(BigInteger smaller, BigInteger larger)
		{
			BigInteger rest;

			smaller = smaller.Abs();
			larger = larger.Abs();

			if (smaller == 0)
				return larger;
			else
			{
				if (larger == 0)
					return smaller;
			}
				

			// the GCD algorithm requires second >= first
			if(smaller > larger)
			{
				rest = larger;
				larger = smaller;
				smaller = rest;
			}
      
			while((rest = larger%smaller) != 0)
			{
				larger = smaller; 
        smaller = rest;
			}
			return smaller;
		}
예제 #25
0
        /// <summary>
        /// Multiply a BigInteger by the given power of two.
        /// </summary>
        /// <param name="number">The BigInteger to multiply by a power of two and replace with the product</param>
        /// <param name="shift">The power of two to multiply it by</param>
        private static void ShiftLeft(ref BigInteger number, uint shift)
        {
            var powerOfTwo = BigInteger.Pow(BigTwo, shift);

            number = number * powerOfTwo;
        }
예제 #26
0
        /// <summary>
        /// Multiply a BigInteger by the given power of ten.
        /// </summary>
        /// <param name="number">The BigInteger to multiply by a power of ten and replace with the product</param>
        /// <param name="power">The power of ten to multiply it by</param>
        private static void MultiplyByPowerOfTen(ref BigInteger number, uint power)
        {
            var powerOfTen = BigInteger.Pow(BigTen, power);

            number = number * powerOfTen;
        }
예제 #27
0
    public static bool GetComponents(this double d, out BigInteger numerator, out BigInteger denominator)
    {
      if (double.IsNaN(d))
      {
        numerator = denominator = 0;
        return false;
      }

      if (double.IsNegativeInfinity(d))
      {
        numerator = -1;
        denominator = 0;
        return false;
      }

      if (double.IsPositiveInfinity(d))
      {
        numerator = 1;
        denominator = 0;
        return false;
      }

      if (d == 0.0)
      {
        numerator = 0;
        denominator = 1;
        return true;
      }

      var r = BitConverter.DoubleToInt64Bits(d);

      var m = GetMantissa(r);
      var e = GetExponent(r);
      var s = GetSign(r) == 0 ? 1 : -1;

      const int BIAS = 1023;
      var re = e - BIAS;

      var exp = (((BigInteger)1) << Math.Abs(re));

      if (re < 0)
      {
        denominator = MANTISSA * s * exp;
        numerator = (MANTISSA + m);
      }
      else
      {
        denominator = MANTISSA * s;
        numerator = exp * (MANTISSA + m);
      }
      

      return true;
    }