Ejemplo n.º 1
0
    static public string ToGoldStringKR(long bigInteger)
    {
        string output = "";

        if (BigInteger.Compare(bigInteger, new BigInteger(10000)) == -1)
        {
            output = bigInteger.ToString();
        }
        else if (BigInteger.Compare(bigInteger, new BigInteger(100000000)) == -1)
        {
            string strTmp = bigInteger.ToString();

            output = strTmp.Substring(0, strTmp.Length - 1 - 3) + "만" +
                     strTmp.Substring(strTmp.Length - 1 - 3);
        }
        else if (BigInteger.Compare(bigInteger, new BigInteger(1000000000000)) == -1)
        {
            string strTmp = bigInteger.ToString();

            output = strTmp.Substring(0, strTmp.Length - 8) + "억" +
                     strTmp.Substring(strTmp.Length - 8, 4) + "만";
            /* + strTmp.Substring(strTmp.Length - 1 - 3);*/
        }
        else if (BigInteger.Compare(bigInteger, new BigInteger(10000000000000000)) == -1)
        {
            string strTmp = bigInteger.ToString();

            output = strTmp.Substring(0, strTmp.Length - 12) + "조" +
                     strTmp.Substring(strTmp.Length - 12, 4) + "억";

            /*+ strTmp.Substring(strTmp.Length - 8, 4) + "만"
             + strTmp.Substring(strTmp.Length - 4);*/
        }
        else if (BigInteger.Compare(bigInteger, new BigInteger(10000000000000000000)) == -1)
        {
            string strTmp = bigInteger.ToString();

            output = strTmp.Substring(0, strTmp.Length - 16) + "경" +
                     strTmp.Substring(strTmp.Length - 16, 4) + "조";

            /*+ strTmp.Substring(strTmp.Length - 12, 4) + "억"
             + strTmp.Substring(strTmp.Length - 8, 4) + "만"
             + strTmp.Substring(strTmp.Length - 4);*/
        }
        return(output);
    }
Ejemplo n.º 2
0
        private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
        {
            bool expectedEquals      = 0 == expectedResult;
            bool expectedLessThan    = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));
            Assert.Equal(expectedEquals, y.Equals(x));

            Assert.Equal(expectedEquals, x.Equals((Object)y));
            Assert.Equal(expectedEquals, y.Equals((Object)x));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
            VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");

            VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
            VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), y.GetHashCode());
                Assert.Equal(x.ToString(), y.ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(y.GetHashCode(), y.GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Ejemplo n.º 3
0
            public static HassiumObject lesserthanorequal(VirtualMachine vm, HassiumObject self, SourceLocation location, params HassiumObject[] args)
            {
                var BigInt    = (self as HassiumBigInt).BigInt;
                var bigintarg = args[0] as HassiumBigInt;

                if (bigintarg != null)
                {
                    return(new HassiumBool(BigInteger.Compare(BigInt, (bigintarg as HassiumBigInt).BigInt) <= 0));
                }
                var intarg = args[0] as HassiumInt;

                if (intarg != null)
                {
                    return(new HassiumBool(BigInteger.Compare(BigInt, (intarg as HassiumInt).Int) <= 0));
                }
                vm.RaiseException(HassiumConversionFailedException.ConversionFailedExceptionTypeDef._new(vm, null, location, args[0], Number));
                return(Null);
            }
Ejemplo n.º 4
0
        public int CompareTo(NodeId other)
        {
            if ((object)other == null)
            {
                return(1);
            }

            BigInteger.Sign s = _value.Compare(other._value);
            if (s == BigInteger.Sign.Zero)
            {
                return(0);
            }
            if (s == BigInteger.Sign.Positive)
            {
                return(1);
            }
            return(-1);
        }
Ejemplo n.º 5
0
    public int CompareTo(BigFloat other)
    {
        if (BigFloat.Equals(other, null))
        {
            throw new ArgumentNullException("other");
        }

        //Make copies
        BigInteger one = this.numerator;
        BigInteger two = other.numerator;

        //cross multiply
        one *= other.denominator;
        two *= this.denominator;

        //test
        return(BigInteger.Compare(one, two));
    }
Ejemplo n.º 6
0
        private static Matrix GenerateValues(int rows, int cols)
        {
            Console.Clear();
            var        total    = BigInteger.Multiply(new BigInteger(rows), new BigInteger(cols));
            var        current  = new BigInteger(0);
            BigInteger progress = new BigInteger(0);

            Console.WriteLine($"GENERATION. Total: {total}");

            using (var sw = new StreamWriter($"values_{rows}_{cols}", false))
            {
                for (var i = 0; i < rows; i++)
                {
                    for (var c = 0; c < cols; c++)
                    {
                        var value = new Random((int)DateTime.Now.Ticks).Next(0, 1000 * 1000);
                        sw.Write(value);
                        sw.Write(';');


                        current = BigInteger.Add(current, 1);

                        var accuracy        = 100000;
                        var currentProgress = BigInteger.Divide(BigInteger.Multiply(current, 100 * accuracy), total);
                        var result          = BigInteger.Compare(progress, currentProgress);
                        if (result < 0)
                        {
                            var rem = new BigInteger();
                            BigInteger.DivRem(currentProgress, accuracy, out rem);
                            Console.SetCursorPosition(0, 1);
                            Console.WriteLine($"GENERATION. Progress: {BigInteger.Divide(currentProgress, accuracy)},{rem}");
                        }
                        progress = currentProgress;
                    }
                    sw.Write('_');
                }
                sw.Flush();
            }

            Console.WriteLine("GENERATION. All processes completed");

            return(null);
        }
    private void TryParse1()
    {
        // <Snippet1>
        BigInteger number1, number2;
        bool       succeeded1 = BigInteger.TryParse("-12347534159895123", out number1);
        bool       succeeded2 = BigInteger.TryParse("987654321357159852", out number2);

        if (succeeded1 && succeeded2)
        {
            number1 *= 3;
            number2 *= 2;
            switch (BigInteger.Compare(number1, number2))
            {
            case -1:
                Console.WriteLine("{0} is greater than {1}.", number2, number1);
                break;

            case 0:
                Console.WriteLine("{0} is equal to {1}.", number1, number2);
                break;

            case 1:
                Console.WriteLine("{0} is greater than {1}.", number1, number2);
                break;
            }
        }
        else
        {
            if (!succeeded1)
            {
                Console.WriteLine("Unable to initialize the first BigInteger value.");
            }

            if (!succeeded2)
            {
                Console.WriteLine("Unable to initialize the second BigInteger value.");
            }
        }
        // The example displays the following output:
        //      1975308642714319704 is greater than -37042602479685369.
        // </Snippet1>
    }
Ejemplo n.º 8
0
        public static BigInteger Height(BigInteger n, BigInteger m)
        {
            if (BigInteger.Compare(n, BigInteger.Zero) == 0 || BigInteger.Compare(m, BigInteger.Zero) == 0)
            {
                return(BigInteger.Zero);
            }

            BigInteger result = 1;
            BigInteger total  = 0;

            BigInteger value = 1;

            for (BigInteger k = 1; k <= n; k++)
            {
                value  = value * (m - k + 1) / k;
                total += value;
            }

            return(total);
        }
Ejemplo n.º 9
0
        public int CompareTo(BigDecimal other)
        {
            var sdiff = this.Scale - other.Scale;

            if (sdiff == 0)
            {
                return(BigInteger.Compare(this.IntVal, other.IntVal));
            }

            if (sdiff < 0)
            {
                var aValMultiplied = BigInteger.Multiply(this.IntVal, BigInteger.Pow(10, -sdiff));
                return(aValMultiplied.CompareTo(other.IntVal));
            }

            // sdiff > 0
            var bValMultiplied = BigInteger.Multiply(other.IntVal, BigInteger.Pow(10, sdiff));

            return(BigInteger.Compare(this.IntVal, bValMultiplied));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            #region BigInteger

            BigInteger BigInt1 = new BigInteger(ulong.MaxValue);
            BigInteger BigInt2 = new BigInteger(ulong.MaxValue);
            Console.WriteLine(BigInteger.Add(BigInt1, BigInt2).ToString());

            BigInteger aBigBigger;
            BigInteger aBigSmaller;
            BigInteger.TryParse("999999999999999999999999999999999999999999999999999999999999999999999999999999999999", out aBigBigger);
            BigInteger.TryParse("999999999999999999999999999999999999999999999999999999999999999999999999999999999998", out aBigSmaller);

            if (BigInteger.Compare(aBigBigger, aBigSmaller) > 0)
            {
                Console.WriteLine(aBigBigger);
            }

            #endregion BigInteger

            #region Truple

            for (Int16 i = 0; i <= 25; i++)
            {
                for (Int16 j = 1; j <= 5; j++)
                {
                    var tuple = DivAndRemainder(i, j);
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\n", i, j, tuple.Item1, tuple.Item2);
                }
            }

            #endregion

            #region python

            IronPythonCall.CallScript();

            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 11
0
        public void UInt128BigIntegerAgreement()
        {
            BigInteger b = BigInteger.Parse(UInt128.MaxValue.ToString()) + 1;

            foreach (UInt128 u in GetRandomUInt128(new Random(2), 16))
            {
                BigInteger u1 = (BigInteger)u;
                foreach (UInt128 v in GetRandomUInt128(new Random(3), 16))
                {
                    BigInteger v1 = (BigInteger)v;

                    // Comparison
                    Assert.IsTrue(UInt128.Compare(u, v) == BigInteger.Compare(u1, v1));
                    Assert.IsTrue((u < v) == (u1 < v1));
                    Assert.IsTrue((u > v) == (u1 > v1));

                    // Sum
                    UInt128    s  = u + v;
                    BigInteger s1 = (u1 + v1) % b;
                    Assert.IsTrue((BigInteger)s == s1);

                    // Difference
                    if (u >= v)
                    {
                        UInt128    d  = u - v;
                        BigInteger d1 = u1 - v1;
                        Assert.IsTrue((BigInteger)d == d1);
                    }

                    // Product
                    UInt128    p  = u * v;
                    BigInteger p1 = (u1 * v1) % b;
                    Assert.IsTrue((BigInteger)p == p1);

                    // Quotient
                    UInt128    q  = u / v;
                    BigInteger q1 = u1 / v1;
                    Assert.IsTrue((BigInteger)q == q1);
                }
            }
        }
Ejemplo n.º 12
0
        public void GenerateFibonacciSequence_LimitIs16_Sequence()
        {
            bool expected = true;
            bool actual   = true;
            IEnumerable <BigInteger> arrayActual = Generator.GenerateFibonacciSequence(3);

            int[] arrayExpected = new int[] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 };
            int   i             = 0;

            foreach (var number in arrayActual)
            {
                if (BigInteger.Compare(number, arrayExpected[i]) != 0)
                {
                    actual = false;
                }

                i++;
            }

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 13
0
        public void GeneratePrimeSequence_LimitIs7_Sequence()
        {
            bool expected = true;
            bool actual   = true;
            IEnumerable <BigInteger> arrayActual = Generator.GeneratePrimeSequence(7);

            int[] arrayExpected = new int[] { 1, 3, 5, 7, 9, 11, 13 };
            int   i             = 0;

            foreach (var number in arrayActual)
            {
                if (BigInteger.Compare(number, arrayExpected[i]) != 0)
                {
                    actual = false;
                }

                i++;
            }

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 14
0
        internal static bool EqLiteralExprs(LiteralExpr e0, LiteralExpr e1)
        {
            if (e0.Value is bool && e1.Value is bool)
            {
                return(((bool)e0.Value) == ((bool)e1.Value));
            }
            else if (e0.Value is int && e1.Value is int)
            {
                return(((int)e0.Value) == ((int)e1.Value));
            }
            else if (e0.Value is BigInteger && e1.Value is BigInteger)
            {
                return(BigInteger.Compare((BigInteger)e0.Value, (BigInteger)e1.Value) == 0);
            }
            else if (e0.Value is string && e1.Value is string)
            {
                return(((string)e0.Value).Equals((string)e1.Value));
            }

            return(false);
        }
Ejemplo n.º 15
0
        private static IEnumerable <int> GenDigits()
        {
            var k  = 1;
            var n1 = new BigInteger(4);
            var n2 = new BigInteger(3);
            var d  = BigInteger.One;

            while (true)
            {
                // digit
                var u = BigInteger.Divide(n1, d);
                var v = BigInteger.Divide(n2, d);

                if (BigInteger.Compare(u, v) == 0)
                {
                    yield return((int)u);

                    // extract
                    u  = BigInteger.Multiply(u, -10);
                    u  = BigInteger.Multiply(u, d);
                    n1 = BigInteger.Multiply(n1, 10);
                    n1 = BigInteger.Add(n1, u);
                    n2 = BigInteger.Multiply(n2, 10);
                    n2 = BigInteger.Add(n2, u);
                }
                else
                {
                    // produce
                    var k2 = k * 2;
                    u = BigInteger.Multiply(n1, k2 - 1);
                    v = BigInteger.Add(n2, n2);
                    var w = BigInteger.Multiply(n1, k - 1);
                    n1 = BigInteger.Add(u, v);
                    u  = BigInteger.Multiply(n2, k + 2);
                    n2 = BigInteger.Add(w, u);
                    d  = BigInteger.Multiply(d, k2 + 1);
                    k++;
                }
            }
        }
Ejemplo n.º 16
0
        public BigInteger FindOrderOfGroup()
        {
            var ret = BigInteger.Zero;

            var q = Curve.CalculateMultiplication(Point, BigInteger.Add(Curve.Modulo, BigInteger.One));
            var m = BigInteger.Add(Curve.Modulo.SqareRoot2().SqareRoot2(), BigInteger.One);

            for (var j = BigInteger.One; BigInteger.Compare(j, m) < 1; j = BigInteger.Add(j, BigInteger.One))
            {
                var jp = Curve.CalculateMultiplication(Point, j);

                for (var k = BigInteger.Multiply(m, BigInteger.MinusOne); BigInteger.Compare(k, m) < 1; k = BigInteger.Add(k, BigInteger.One))
                {
                    var twoMK = BigInteger.Multiply(BigInteger.Multiply(new BigInteger(2), m), k);
                    var cp    = Curve.CalculateMultiplication(Point, twoMK);
                    cp = Curve.CalculateAddition(cp, q);

                    if (BigInteger.Compare(cp.XCoordinate, jp.XCoordinate) == 0)
                    {
                        ret = BigInteger.Add(Curve.Modulo, BigInteger.Add(BigInteger.One, twoMK));

//                        Console.WriteLine($"Order of group: {ret} +- {j}");

                        var ret1 = BigInteger.Add(ret, j);
                        var ret2 = BigInteger.Subtract(ret, j);

                        if (CheckInfinity(ret1))
                        {
                            return(ret1);
                        }
                        else if (CheckInfinity(ret2))
                        {
                            return(ret2);
                        }
                    }
                }
            }

            return(ret);
        }
Ejemplo n.º 17
0
        // This is how the mining works!
        public void Mine(int difficulty)
        {
            var maxTarget = new BigInteger(HexToLittleEndianSwap(MAX_TARGET_VALUE));
            var diff      = new BigInteger(difficulty);
            var target    = BigInteger.Divide(maxTarget, diff);

            Console.WriteLine(string.Format("Target: (Difficulty: {0})", this._difficulty));
            Utility.WriteHex(HexToBigEndianSwap(target.ToByteArray(), 32));
            this._bits = CompBits(HexToBigEndianSwap(target.ToByteArray(), 32));

            var value = new BigInteger();

            do
            {
                this._nonce++;
                this._hash = this.CalculateHash();
                value      = new BigInteger(HexToLittleEndianSwap(this._hash));
                //Console.WriteLine("Mining: " + BitConverter.ToString(this._hash));
            }while (BigInteger.Compare(value, target) > 0);
            Console.WriteLine("Block has been mined: ");
            Utility.WriteHex(this._hash);
        }
Ejemplo n.º 18
0
        public void CompareOps()
        {
            long[] values = new long [] { -100000000000L, -1000, -1, 0, 1, 1000, 100000000000L };
            for (int i = 0; i < values.Length; ++i)
            {
                for (int j = 0; j < values.Length; ++j)
                {
                    var a = new BigInteger(values [i]);
                    var b = new BigInteger(values [j]);

                    Assert.AreEqual(values [i].CompareTo(values [j]), a.CompareTo(b), "#a_" + i + "_" + j);
                    Assert.AreEqual(values [i].CompareTo(values [j]), BigInteger.Compare(a, b), "#b_" + i + "_" + j);

                    Assert.AreEqual(values [i] < values [j], a < b, "#c_" + i + "_" + j);
                    Assert.AreEqual(values [i] <= values [j], a <= b, "#d_" + i + "_" + j);
                    Assert.AreEqual(values [i] == values [j], a == b, "#e_" + i + "_" + j);
                    Assert.AreEqual(values [i] != values [j], a != b, "#f_" + i + "_" + j);
                    Assert.AreEqual(values [i] >= values [j], a >= b, "#g_" + i + "_" + j);
                    Assert.AreEqual(values [i] > values [j], a > b, "#h_" + i + "_" + j);
                }
            }
        }
Ejemplo n.º 19
0
    public static NumericRelationship Compare(ValueType value1, ValueType value2)
    {
        if (!IsNumeric(value1))
        {
            throw new ArgumentException("value1 is not a number.");
        }
        else if (!IsNumeric(value2))
        {
            throw new ArgumentException("value2 is not a number.");
        }

        // Use BigInteger as common integral type
        if (IsInteger(value1) && IsInteger(value2))
        {
            BigInteger bigint1 = (BigInteger)value1;
            BigInteger bigint2 = (BigInteger)value2;
            return((NumericRelationship)BigInteger.Compare(bigint1, bigint2));
        }
        // At least one value is floating point; use Double.
        else
        {
            Double dbl1 = 0;
            Double dbl2 = 0;
            try {
                dbl1 = Convert.ToDouble(value1);
            }
            catch (OverflowException) {
                Console.WriteLine("value1 is outside the range of a Double.");
            }
            try {
                dbl2 = Convert.ToDouble(value2);
            }
            catch (OverflowException) {
                Console.WriteLine("value2 is outside the range of a Double.");
            }
            return((NumericRelationship)dbl1.CompareTo(dbl2));
        }
    }
Ejemplo n.º 20
0
        public static int Compare(HNumber left, HNumber right)
        {
            if (left.Sign > right.Sign)
            {
                return(1);
            }
            else if (left.Sign < right.Sign)
            {
                return(-1);
            }

            int leftTheoreticalExponent  = left.Exponent + left.DigitCount;
            int rightTheoreticalExponent = right.Exponent + right.DigitCount;

            if (leftTheoreticalExponent == rightTheoreticalExponent)
            {
                return(BigInteger.Compare(left.Mantissa, right.Mantissa));
            }
            else
            {
                return((leftTheoreticalExponent * left.Sign) > (rightTheoreticalExponent * right.Sign) ? 1 : -1);
            }
        }
Ejemplo n.º 21
0
  { [STAThread]             // needed for Clipboard
    static void Main(string[] args)
    {
        /* Variables ********************************************************************/
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        BigInteger a, b, c, d, n;
        int        flag;

        /* Assign Data ******************************************************************/
        n = 224869951114090657;         // p=675730721, q=332780417 (~55 seconds)
        a = Isqrt(n) + 1;
        b = 0;
        c = a * a;
        d = n;
        Console.WriteLine("\t Basic Fermat Factoring n = {0}", n);

        /* Algorithm ********************************************************************/
        do
        {
            flag = BigInteger.Compare(c, d);                // test & set flag
            if (flag < 0)
            {
                c += a++ + a;                               // enlarge "c"
            }
            if (flag > 0)
            {
                d += b++ + b;                               // enlarge "d"
            }
        } while (flag != 0);

        /* Output Data ******************************************************************/
        Console.WriteLine("\n p = {0}\n q = {1}", a + b, a - b);
        Console.WriteLine(" Press <Enter> to write to Paste Buffer");
        Console.Read(); Console.Read();
        sb.Append(a + b + "\n"); sb.Append(a - b + "\n"); // store in a string
        Clipboard.SetText(sb.ToString());                 // output to clipboard
        Console.Read();
    }                                                     //end of Main()
Ejemplo n.º 22
0
 private BigInteger.Sign bignum_cmp(BigInteger a, BigInteger b)
 {
     return a.Compare(b);
 }
Ejemplo n.º 23
0
 public SqlInt32 Compare(SqlBigInteger other)
 {
     return(_value.HasValue && other._value.HasValue ? BigInteger.Compare(_value.Value, other._value.Value) : SqlInt32.Null);
 }
Ejemplo n.º 24
0
        private void ParseUnmanagedTransactions(AltruismServices svc)
        {
            BigInteger big10Finney = BigInteger.Parse("10000000000000000"); // 0.01 ETH
            BigInteger big30Finney = BigInteger.Parse("30000000000000000"); // 0.03 ETH
            BigInteger big40Finney = BigInteger.Parse("40000000000000000"); // 0.04 ETH
            BigInteger bigDivision = new BigInteger(3.0);
            // Get the unmanaged tx
            IEnumerable <TransactionModel> toManage = svc.GetUnmanagedTransactions();

            if (toManage != null && toManage.Any())
            {
                // Get the past contributors
                List <string> contributors = svc.GetContributors();
                if (contributors == null || contributors.Count < 5)
                {
                    // I hack the third system if contributors are less than 5.
                    // This is to prevent people to invest at the start time more than one time to get more token with less eth
                    contributors.Add(ownerAddress);
                }
                foreach (TransactionModel model in toManage)
                {
                    if (model.isError != 0)
                    {
                        log.Debug("TX on error : " + model.hash);
                        // This tx is on error => Done.
                        svc.SetManaged(model.hash, false, false);
                        continue;
                    }
                    if (model.to != ownerContract)
                    {
                        log.Debug("TX not for us : " + model.hash);
                        // This tx does not concern us -> Done.
                        svc.SetManaged(model.hash, false, false);
                        continue;
                    }
                    if (BigInteger.Compare(model.BigValue, big10Finney) < 0)
                    {
                        // This tx is less than 0.01 ETH. Must be on error. Do I jump here ? => Done.
                        log.Debug("TX not in error ? : " + model.hash);
                        svc.SetManaged(model.hash, false, false);
                        continue;
                    }
                    log.Debug("tx from : " + model.from);
                    if (!contributors.Contains(model.from))
                    {
                        // Hoo a new contributor. Save it.
                        log.Debug("New contributor added : " + model.from);
                        contributors.Add(model.from);
                        svc.AddContributor(model.from);
                        if (contributors.Count > 5)
                        {
                            // If there are more than 5 contributors, I remove myself (if i'm in)
                            contributors.Remove(ownerAddress);
                        }
                    }
                    if (BigInteger.Compare(model.BigValue, big40Finney) == 0)
                    {
                        // Hacked mode enabled => Done.
                        log.Debug("Hacked mode : " + model.hash);
                        svc.SetManaged(model.hash, false, true);
                        continue;
                    }
                    if (BigInteger.Compare(model.BigValue, big30Finney) < 0)
                    {
                        // No Altruism mode => Done.
                        log.Debug("No hack, no altruist : " + model.hash);
                        svc.SetManaged(model.hash, false, false);
                        continue;
                    }
                    // Altruist one \o/
                    // Take a third of the value
                    BigInteger toSend = BigInteger.Divide(model.BigValue, bigDivision);
                    log.Debug("The altruist send : " + model.value);
                    log.Debug("The winner get : " + toSend.ToString());
                    Random rnd = new Random();
                    // Pick a random number
                    int next = rnd.Next(contributors.Count);
                    // Get the winner
                    string winnerAddress = contributors.ElementAt(next);
                    log.Debug("And the winner is : " + toSend.ToString());
                    // Unlock my account
                    Task <bool> unlocked = web3.Personal.UnlockAccount.SendRequestAsync(ownerAddress, ownerPassword, new HexBigInteger(60));
                    if (unlocked.Result)
                    {
                        TransactionInput input = new TransactionInput();
                        input.From  = ownerAddress;
                        input.To    = winnerAddress;
                        input.Value = new HexBigInteger(toSend);
                        // Generate the tx
                        Task <string> txHash = web3.Eth.Transactions.SendTransaction.SendRequestAsync(input);
                        // Get the receipt tx
                        Task <TransactionReceipt> receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txHash.Result);
                        // Save the tx => Done.
                        svc.SetManaged(model.hash, true, false, txHash.Result);
                        log.Info("Successfully send at " + txHash.Result);
                    }
                    else
                    {
                        log.Fatal("The unlock didn't work for the tx " + model.hash);
                    }
                }
            }
        }
Ejemplo n.º 25
0
 public static int Compare(BigInteger /*!*/ self, int other)
 {
     return(BigInteger.Compare(self, (BigInteger)other));
 }
Ejemplo n.º 26
0
 public static int Compare(BigInteger /*!*/ self, [NotNull] BigInteger /*!*/ other)
 {
     return(BigInteger.Compare(self, other));
 }
 static bool ZPKrecieveZ(BigInteger n, BigInteger z, BigInteger x)
 => BigInteger.Compare(BigInteger.ModPow(x, TWO, n), z) == 0;
 static bool Verify(BigInteger s, BigInteger m, BigInteger n)
 => BigInteger.Compare(DeformatMessage(BigInteger.ModPow(s, TWO, n), n), m) == 0;
Ejemplo n.º 29
0
        private static unsafe void Dragon4(double value, int precision, ref NumberBuffer number)
        {
            // ========================================================================================================================================
            // This implementation is based on the paper: https://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf
            // Besides the paper, some of the code and ideas are modified from http://www.ryanjuckett.com/programming/printing-floating-point-numbers/
            // You must read these two materials to fully understand the code.
            //
            // Note: we only support fixed format input.
            // ========================================================================================================================================
            //
            // Overview:
            //
            // The input double number can be represented as:
            // value = f * 2^e = r / s.
            //
            // f: the output mantissa. Note: f is not the 52 bits mantissa of the input double number.
            // e: biased exponent.
            // r: numerator.
            // s: denominator.
            // k: value = d0.d1d2 . . . dn * 10^k

            // Step 1:
            // Extract meta data from the input double value.
            //
            // Refer to IEEE double precision floating point format.
            ulong f = (ulong)(ExtractFractionAndBiasedExponent(value, out int e));
            int   mantissaHighBitIndex = (e == -1074) ? (int)(BigInteger.LogBase2(f)) : 52;

            // Step 2:
            // Estimate k. We'll verify it and fix any error later.
            //
            // This is an improvement of the estimation in the original paper.
            // Inspired by http://www.ryanjuckett.com/programming/printing-floating-point-numbers/
            //
            // LOG10V2 = 0.30102999566398119521373889472449
            // DRIFT_FACTOR = 0.69 = 1 - log10V2 - epsilon (a small number account for drift of floating point multiplication)
            int k = (int)(Math.Ceiling(((mantissaHighBitIndex + e) * Log10V2) - DriftFactor));

            // Step 3:
            // Store the input double value in BigInteger format.
            //
            // To keep the precision, we represent the double value as r/s.
            // We have several optimization based on following table in the paper.
            //
            //     ----------------------------------------------------------------------------------------------------------
            //     |               e >= 0                   |                         e < 0                                 |
            //     ----------------------------------------------------------------------------------------------------------
            //     |  f != b^(P - 1)  |  f = b^(P - 1)      | e = min exp or f != b^(P - 1) | e > min exp and f = b^(P - 1) |
            // --------------------------------------------------------------------------------------------------------------
            // | r |  f * b^e * 2     |  f * b^(e + 1) * 2  |          f * 2                |            f * b * 2          |
            // --------------------------------------------------------------------------------------------------------------
            // | s |        2         |        b * 2        |          b^(-e) * 2           |            b^(-e + 1) * 2     |
            // --------------------------------------------------------------------------------------------------------------
            //
            // Note, we do not need m+ and m- because we only support fixed format input here.
            // m+ and m- are used for free format input, which need to determine the exact range of values
            // that would round to value when input so that we can generate the shortest correct number.digits.
            //
            // In our case, we just output number.digits until reaching the expected precision.

            var r = new BigInteger(f);
            var s = new BigInteger(0);

            if (e >= 0)
            {
                // When f != b^(P - 1):
                // r = f * b^e * 2
                // s = 2
                // value = r / s = f * b^e * 2 / 2 = f * b^e / 1
                //
                // When f = b^(P - 1):
                // r = f * b^(e + 1) * 2
                // s = b * 2
                // value = r / s =  f * b^(e + 1) * 2 / b * 2 = f * b^e / 1
                //
                // Therefore, we can simply say that when e >= 0:
                // r = f * b^e = f * 2^e
                // s = 1

                r.ShiftLeft((uint)(e));
                s.SetUInt64(1);
            }
            else
            {
                // When e = min exp or f != b^(P - 1):
                // r = f * 2
                // s = b^(-e) * 2
                // value = r / s = f * 2 / b^(-e) * 2 = f / b^(-e)
                //
                // When e > min exp and f = b^(P - 1):
                // r = f * b * 2
                // s = b^(-e + 1) * 2
                // value = r / s =  f * b * 2 / b^(-e + 1) * 2 = f / b^(-e)
                //
                // Therefore, we can simply say that when e < 0:
                // r = f
                // s = b^(-e) = 2^(-e)

                BigInteger.ShiftLeft(1, (uint)(-e), ref s);
            }

            // According to the paper, we should use k >= 0 instead of k > 0 here.
            // However, if k = 0, both r and s won't be changed, we don't need to do any operation.
            //
            // Following are the Scheme code from the paper:
            // --------------------------------------------------------------------------------
            // (if (>= est 0)
            // (fixup r (* s (exptt B est)) m+ m− est B low-ok? high-ok? )
            // (let ([scale (exptt B (− est))])
            // (fixup (* r scale) s (* m+ scale) (* m− scale) est B low-ok? high-ok? ))))
            // --------------------------------------------------------------------------------
            //
            // If est is 0, (* s (exptt B est)) = s, (* r scale) = (* r (exptt B (− est)))) = r.
            //
            // So we just skip when k = 0.

            if (k > 0)
            {
                BigInteger poweredValue = new BigInteger(0);
                BigInteger.Pow10((uint)(k), ref poweredValue);
                s.Multiply(ref poweredValue);
            }
            else if (k < 0)
            {
                BigInteger poweredValue = new BigInteger(0);
                BigInteger.Pow10((uint)(-k), ref poweredValue);
                r.Multiply(ref poweredValue);
            }

            if (BigInteger.Compare(ref r, ref s) >= 0)
            {
                // The estimation was incorrect. Fix the error by increasing 1.
                k += 1;
            }
            else
            {
                r.Multiply10();
            }

            number.scale = (k - 1);

            // This the prerequisite of calling BigInteger.HeuristicDivide().
            BigInteger.PrepareHeuristicDivide(ref r, ref s);

            // Step 4:
            // Calculate number.digits.
            //
            // Output number.digits until reaching the last but one precision or the numerator becomes zero.

            int digitsNum    = 0;
            int currentDigit = 0;

            while (true)
            {
                currentDigit = (int)(BigInteger.HeuristicDivide(ref r, ref s));

                if (r.IsZero() || ((digitsNum + 1) == precision))
                {
                    break;
                }

                number.digits[digitsNum] = (char)('0' + currentDigit);
                digitsNum++;

                r.Multiply10();
            }

            // Step 5:
            // Set the last digit.
            //
            // We round to the closest digit by comparing value with 0.5:
            //  compare( value, 0.5 )
            //  = compare( r / s, 0.5 )
            //  = compare( r, 0.5 * s)
            //  = compare(2 * r, s)
            //  = compare(r << 1, s)

            r.ShiftLeft(1);
            int  compareResult = BigInteger.Compare(ref r, ref s);
            bool isRoundDown   = compareResult < 0;

            // We are in the middle, round towards the even digit (i.e. IEEE rouding rules)
            if (compareResult == 0)
            {
                isRoundDown = (currentDigit & 1) == 0;
            }

            if (isRoundDown)
            {
                number.digits[digitsNum] = (char)('0' + currentDigit);
                digitsNum++;
            }
            else
            {
                char *pCurrentDigit = (number.GetDigitsPointer() + digitsNum);

                // Rounding up for 9 is special.
                if (currentDigit == 9)
                {
                    // find the first non-nine prior digit
                    while (true)
                    {
                        // If we are at the first digit
                        if (pCurrentDigit == number.GetDigitsPointer())
                        {
                            // Output 1 at the next highest exponent
                            *pCurrentDigit = '1';
                            digitsNum++;
                            number.scale += 1;
                            break;
                        }

                        pCurrentDigit--;
                        digitsNum--;

                        if (*pCurrentDigit != '9')
                        {
                            // increment the digit
                            *pCurrentDigit += (char)(1);
                            digitsNum++;
                            break;
                        }
                    }
                }
                else
                {
                    // It's simple if the digit is not 9.
                    *pCurrentDigit = (char)('0' + currentDigit + 1);
                    digitsNum++;
                }
            }

            while (digitsNum < precision)
            {
                number.digits[digitsNum] = '0';
                digitsNum++;
            }

            number.digits[precision] = '\0';

            number.scale++;
            number.sign = double.IsNegative(value);
        }
Ejemplo n.º 30
0
 public void Factorial_BigInteger_Tests(int x, int expected)
 {
     Assert.IsTrue(BigInteger.Compare(new BigInteger(expected), Function.Factorial(new BigInteger(x))) == 0);
 }
        private bool IsProbablePrime(BigInteger source, int certainty)
        {
            if (BigInteger.Compare(source, BigInteger.Add(BigInteger.One, BigInteger.One)) == 0 || BigInteger.Compare(source, BigInteger.Add(BigInteger.Add(BigInteger.One, BigInteger.One), BigInteger.One)) == 0)
            {
                return(true);
            }
            if (BigInteger.Compare(source, BigInteger.Add(BigInteger.One, BigInteger.One)) == -1 || BigInteger.Remainder(source, BigInteger.Add(BigInteger.One, BigInteger.One)) == 0)
            {
                return(false);
            }

            BigInteger d = BigInteger.Subtract(source, BigInteger.One);
            int        s = 0;

            while (BigInteger.Compare(BigInteger.Remainder(d, BigInteger.Add(BigInteger.One, BigInteger.One)), BigInteger.Zero) == 0)
            {
                d  = BigInteger.Divide(d, BigInteger.Add(BigInteger.One, BigInteger.One));
                s += 1;
            }

            RandomNumberGenerator rng = RandomNumberGenerator.Create();

            byte[]     bytes = new byte[source.ToByteArray().Length];
            BigInteger a;

            for (int i = 0; i < certainty; i++)
            {
                do
                {
                    rng.GetBytes(bytes);
                    a = new BigInteger(bytes);
                }while(BigInteger.Compare(a, BigInteger.Add(BigInteger.One, BigInteger.One)) == -1 || BigInteger.Compare(a, BigInteger.Subtract(source, BigInteger.Add(BigInteger.One, BigInteger.One))) >= 0);

                BigInteger x = BigInteger.ModPow(a, d, source);
                if (BigInteger.Compare(x, BigInteger.One) == 0 || BigInteger.Compare(x, BigInteger.Subtract(source, BigInteger.One)) == 0)
                {
                    continue;
                }

                for (int r = 1; r < s; r++)
                {
                    x = BigInteger.ModPow(x, BigInteger.Add(BigInteger.One, BigInteger.One), source);
                    if (BigInteger.Compare(x, BigInteger.One) == 0)
                    {
                        return(false);
                    }
                    if (BigInteger.Compare(x, BigInteger.Subtract(source, BigInteger.One)) == 0)
                    {
                        break;
                    }
                }

                if (BigInteger.Compare(x, BigInteger.Subtract(source, BigInteger.One)) != 0)
                {
                    return(false);
                }
            }
            return(true);
        }