Exemplo n.º 1
0
 // Expected tree for function: ^(FUNC ID ( INT | ID ) expr)
 /** Set up a local evaluator for a nested function call. The evaluator gets the definition
  *  tree of the function; the set of all defined functions (to find locally called ones); a
  *  pointer to the global variable memory; and the value of the function parameter to be
  *  added to the local memory.
  */
 private DebugTreeGrammar(CommonTree function,
              List<CommonTree> functionDefinitions,
              IDictionary<string, BigInteger> globalMemory,
              BigInteger paramValue)
     : this(new CommonTreeNodeStream(function.GetChild(2)), functionDefinitions)
 {
     this.globalMemory = globalMemory;
     localMemory[function.GetChild(1).Text] = paramValue;
 }
Exemplo n.º 2
0
 public void FromDouble()
 {
     for (int i = 0; i < significantNumbers.Length; i++)
     {
         var expected = new System.Numerics.BigInteger(double.Parse(significantNumbers[i]));
         var actual = BigInteger.FromDouble(double.Parse(significantNumbers[i]));
         Assert.AreEqual(expected, Convert(actual), string.Format("Computing FromDouble({0})", significantNumbers[i]));
     }
 }
Exemplo n.º 3
0
 static DecodedBitStreamParser()
 {
     EXP900 = new System.Numerics.BigInteger[16];
     EXP900[0] = System.Numerics.BigInteger.One;
     System.Numerics.BigInteger nineHundred = new System.Numerics.BigInteger(900);
     EXP900[1] = nineHundred;
     for (int i = 2; i < EXP900.Length; i++)
     {
       EXP900[i] = EXP900[i - 1] * nineHundred;
     }
 }
Exemplo n.º 4
0
 internal BigDec(BIM mantissa, int exponent)
 {
     if (mantissa.IsZero) {
     this.mantissa = mantissa;
     this.exponent = 0;
       }
       else {
     while (mantissa % ten == BIM.Zero) {
       mantissa = mantissa / ten;
       exponent = exponent + 1;
     }
     this.mantissa = mantissa;
     this.exponent = exponent;
       }
 }
Exemplo n.º 5
0
        public WheelFast(int N)
        {
            int DIM = N * 2 + 1;

            numWays_IJ = new NumWaysType[DIM][];
            combin = new NumWaysType[DIM][];
            expectedValue = new double[DIM][];
            emptyGondolasCount = new int[DIM][];
            hasGondola = new bool[DIM];
            for (int i = 0; i < numWays_IJ.Length; ++i)
            {
                numWays_IJ[i] = new NumWaysType[DIM];
                combin[i] = new NumWaysType[DIM];
                expectedValue[i] = new double[DIM];
                emptyGondolasCount[i] = new int[DIM];
            }
        }
Exemplo n.º 6
0
        public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            var charCount = GetMaxCharCount(byteCount);

            var numbytes = new byte[byteCount + 1];
            Array.Copy(bytes, byteIndex, numbytes, 0, byteCount);
            var num = new System.Numerics.BigInteger(numbytes);

            charIndex += charCount;
            for (int i = 0; i < charCount; ++i)
            {
                System.Numerics.BigInteger rem;
                num = System.Numerics.BigInteger.DivRem(num, Base, out rem);
                chars[--charIndex] = Alphabet[(int)rem];
            }

            return charCount;
        }
Exemplo n.º 7
0
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var num = new System.Numerics.BigInteger();

            for (int i = 0; i < charCount; ++i)
            {
                num *= Base;
                var index = Alphabet.IndexOf(chars[charIndex + i]);
                if (index == -1)
                {
                    throw new Exception("Illegal character " + chars[charIndex + i] + " at " + (charIndex + i));
                }
                num += index;
            }

            var numbytes = num.ToByteArray();
            var byteCount = GetMaxByteCount(charCount);
            Array.Copy(numbytes, 0, bytes, byteIndex, Math.Min(byteCount, numbytes.Length));

            return byteCount;
        }
        /// <summary>
        /// Reads a C# integer literal into the capture buffer while parsing it
        /// </summary>
        /// <returns>The value the literal represents</returns>
        /// <exception cref="ExpectingException">The input was not valid</exception>

        public object ParseInteger()
        {
            EnsureStarted();
            Expecting('-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            bool neg = ('-' == Current);

            if (neg)
            {
                Advance();
                Expecting('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            }
            System.Numerics.BigInteger i = 0;
            if (!neg)
            {
                i += ((char)Current) - '0';
                while (-1 != Advance() && char.IsDigit((char)Current))
                {
                    i *= 10;
                    i += ((char)Current) - '0';
                }
            }
            else
            {
                i -= ((char)Current) - '0';
                while (-1 != Advance() && char.IsDigit((char)Current))
                {
                    i *= 10;
                    i -= ((char)Current) - '0';
                }
            }
            if (i <= int.MaxValue && i >= int.MinValue)
            {
                return((int)i);
            }
            else if (i <= long.MaxValue && i >= long.MinValue)
            {
                return((long)i);
            }
            return(i);
        }
Exemplo n.º 9
0
 public override RuntimeResult Modulus(Value other)
 {
     if (other.Type == ValueType.INTEGER)
     {
         int otherValue = (int)other.Data;
         if (otherValue == 0)
         {
             return(new RuntimeResult(new RuntimeError(Position, "Division by zero", Context)));
         }
         return(new RuntimeResult(new Int64Value((long)Data % otherValue).SetPositionAndContext(Position, Context)));
     }
     else if (other.Type == ValueType.INT64)
     {
         long otherValue = (long)other.Data;
         if (otherValue == 0)
         {
             return(new RuntimeResult(new RuntimeError(Position, "Division by zero", Context)));
         }
         return(new RuntimeResult(new Int64Value((long)Data % otherValue).SetPositionAndContext(Position, Context)));
     }
     else if (other.Type == ValueType.BIGINTEGER)
     {
         System.Numerics.BigInteger otherValue = (System.Numerics.BigInteger)other.Data;
         if (otherValue == 0)
         {
             return(new RuntimeResult(new RuntimeError(Position, "Division by zero", Context)));
         }
         return(new RuntimeResult(new BigInt((long)Data % otherValue).SetPositionAndContext(Position, Context)));
     }
     else if (other.Type == ValueType.FLOAT)
     {
         double otherValue = (double)other.Data;
         if (otherValue == 0)
         {
             return(new RuntimeResult(new RuntimeError(Position, "Division by zero", Context)));
         }
         return(new RuntimeResult(new FloatValue((long)Data % otherValue).SetPositionAndContext(Position, Context)));
     }
     return(new RuntimeResult(new RuntimeError(Position, "'/' is unsupported between " + Type.ToString().ToLower() + " and " + other.Type.ToString().ToLower(), Context)));
 }
Exemplo n.º 10
0
 public static System.Numerics.BigInteger BinomialCoefficient(System.Numerics.BigInteger k, System.Numerics.BigInteger n)
 {
     if (k < 0 || n < 0)
     {
         throw new System.ArgumentOutOfRangeException("Invalid k or n in binomial coefficient.");
     }
     if (k > n)
     {
         return(BinomialCoefficient(n, k));
     }
     if (k > n - k)
     {
         k = n - k;
     }
     System.Numerics.BigInteger result = 1;
     for (System.Numerics.BigInteger i = 1; i <= k; ++i)
     {
         result *= n - k + i;
         result /= i;
     }
     return(result);
 }
Exemplo n.º 11
0
        static BI Sqrt(BI n)
        {
            BI x0 = 1;

            //Console.WriteLine(">{0}", n);
            for (;;)
            {
                BI x1 = (x0 + n / x0) / 2;
                BI dx = x1 - x0;
                x0 = x1;
                if (-1 <= dx && dx <= 1)
                {
                    break;
                }
                //Console.WriteLine(">{0} {1}", x0, dx);
            }
            while (x0 * x0 > n)
            {
                x0--;
            }
            return(x0);
        }
Exemplo n.º 12
0
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var num = new System.Numerics.BigInteger();

            for (int i = 0; i < charCount; ++i)
            {
                num *= Base;
                var index = Alphabet.IndexOf(chars[charIndex + i]);
                if (index == -1)
                {
                    throw new Exception("Illegal character " + chars[charIndex + i] + " at " + (charIndex + i));
                }
                num += index;
            }

            var numbytes  = num.ToByteArray();
            var byteCount = GetMaxByteCount(charCount);

            Array.Copy(numbytes, 0, bytes, byteIndex, Math.Min(byteCount, numbytes.Length));

            return(byteCount);
        }
Exemplo n.º 13
0
        private static bool fermatsTest(System.Numerics.BigInteger n)
        {
            System.Numerics.BigInteger power = exp(2, n - 1, n);
            if (power != 1)
            {
                return(false);
            }

            power = exp(3, n - 1, n);
            if (power != 1)
            {
                return(false);
            }

            power = exp(5, n - 1, n);
            if (power != 1)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 14
0
        //зашифровать
        private List <string> RSA_Endoce(string s, long e, long n)
        {
            List <string> result = new List <string>();

            System.Numerics.BigInteger bi;

            for (int i = 0; i < s.Length; i++)
            {
                int index = Array.IndexOf(characters, s[i]);

                bi = new System.Numerics.BigInteger(index);
                //  bi = BigInteger.Pow(bi, (int)e);

                System.Numerics.BigInteger n_ = new System.Numerics.BigInteger((int)n);

                bi = bi % n_;

                result.Add(bi.ToString());
            }

            return(result);
        }
Exemplo n.º 15
0
        //расшифровать
        private string RSA_Dedoce(List <string> input, long d, long n)
        {
            string result = "";

            System.Numerics.BigInteger bi;

            foreach (string item in input)
            {
                bi = new System.Numerics.BigInteger(Convert.ToDouble(item));
                bi = System.Numerics.BigInteger.Pow(bi, (int)d);

                System.Numerics.BigInteger n_ = new System.Numerics.BigInteger((int)n);

                bi = bi % n_;

                int index = Convert.ToInt32(bi.ToString());

                result += characters[index].ToString();
            }

            return(result);
        }
Exemplo n.º 16
0
 public static System.Numerics.BigInteger BigIntPow(long b, long exp)
 {
     System.Numerics.BigInteger result = 1;
     if (exp > 0)
     {
         while (exp > 0)
         {
             result *= b;
             --exp;
         }
         return(result);
     }
     else
     {
         while (exp < 0)
         {
             result *= b;
             ++exp;
         }
         return(1 / result);
     }
 }
Exemplo n.º 17
0
        public virtual string SignTransaction(string aTxData, ICurrencyTransaction aValidationInfo)
        {
            if (aValidationInfo.Outputs.Length > 2)
            {
                throw new ArgumentException("Invalid output.");
            }
            var lTxOutput    = aValidationInfo.Outputs.First();
            var lFromAddress = aValidationInfo.Inputs[0].Address.ToLower();
            var lToAddress   = lTxOutput.Address;
            var lKeyIndex    = FAddresses[lFromAddress];
            var lAmount      = lTxOutput.Amount;
            var lTokenData   = !string.IsNullOrEmpty(lTxOutput.Script) ? lTxOutput.Script : null;
            //var lNonceStr = Encoding.Default.GetString(HexStringToByteArray(aTxData)); //I removed this line because biginteger already accepts hex
            string     lCleanHexNonce = string.Concat("0", aTxData.Replace("0x", string.Empty));
            var        lNonce         = BigInteger.Parse(lCleanHexNonce, System.Globalization.NumberStyles.HexNumber);
            var        lGasLimit      = lTokenData == null ? 21000 : 60000;          // number of gass units you can use
            BigInteger lGasPrice      = aValidationInfo.TxFee / lGasLimit;
            var        lChainID       = aValidationInfo.CurrencyId == 10196 ? 3 : 1; //10196 is ropsten but this may be changed to a boolean into currency item
            var        lResult        = (new TransactionSigner()).SignTransaction(GetBinaryPrivateKey((int)lKeyIndex), lChainID, lToAddress, lAmount, lNonce, lGasPrice, lGasLimit, lTokenData);

            return(lResult);
        }
Exemplo n.º 18
0
        public void NullCollationAndCollation2()
        {
            var _testengine = new TestEngine();

            _testengine.AddEntryScript("./TestClasses/Contract_NULL.cs");
            _testengine.Snapshot.Contracts.Add(testengine.EntryScriptHash, new Ledger.ContractState()
            {
                Script   = testengine.EntryContext.Script,
                Manifest = new ContractManifest()
                {
                    Features = ContractFeatures.HasStorage
                }
            });
            {
                var result = _testengine.ExecuteTestCaseStandard("nullCollationAndCollation2", "nes");
                var item   = result.Pop() as Integer;
                var bts    = System.Text.Encoding.ASCII.GetBytes("111");
                var num    = new System.Numerics.BigInteger(bts);

                Assert.IsTrue(item.ToBigInteger() == num);
            }
        }
Exemplo n.º 19
0
 public static Values.Value BigPow(System.Numerics.BigInteger b, System.Numerics.BigInteger exp)
 {
     System.Numerics.BigInteger result = 1;
     if (exp > 0)
     {
         while (exp > 0)
         {
             result *= b;
             --exp;
         }
         return(new Values.BigInt(result));
     }
     else
     {
         while (exp < 0)
         {
             result *= b;
             ++exp;
         }
         return(new Values.FloatValue(1.0 / System.Convert.ToDouble(result.ToString())));
     }
 }
Exemplo n.º 20
0
        // Taken from: http://www.codeproject.com/Articles/16872/Number-base-conversion-class-in-C
        public static string ConvertValue(string value, int sourceRadix, int targetRadix)
        {
            const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";

            System.Numerics.BigInteger bigint = 0;

            for (int index = value.Length - 1; index >= 0; index--)
            {
                bigint += digits.IndexOf(value[index].ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) * System.Numerics.BigInteger.Pow(sourceRadix, value.Length - 1 - index);
            }

            System.Text.StringBuilder result = new StringBuilder();

            System.Numerics.BigInteger workingValue = bigint;
            while (workingValue > 0)
            {
                int digitValue = (int)(workingValue % targetRadix);
                result.Insert(0, digits[digitValue]);
                workingValue = (workingValue - digitValue) / targetRadix;
            }
            return(result.ToString());
        }
Exemplo n.º 21
0
        public static BigInteger Euler(int n)
        {
            if (n % 2 != 0)
            {
                return(0);
            }

            n /= 2;

            Rational[,] m = new Rational[n, n];
            BigInteger bottom  = 1;
            BigInteger counter = 0;

            for (int i = 0; i <= n; i++)
            {
                Rational entry = new Rational(1, bottom);

                for (int j = 0; j < n; j++)
                {
                    int x = i + j - 1;
                    int y = j;

                    if (x >= 0 && x < n && y >= 0 && y < n)
                    {
                        m[x, y] = entry;
                    }
                }

                if (i != n)
                {
                    counter++;
                    bottom *= counter;
                    counter++;
                    bottom *= counter;
                }
            }

            return(AlternateSign((bottom * (new Matrix <Rational, RationalSpace>(m)).Determinant()).Top, n));
        }
Exemplo n.º 22
0
        //this function returns the next integer in the fibonacci sequence
        public string ReadLine(int i)
        {
            System.Numerics.BigInteger first = 0, second = 1, result = 0;   //use big integer to get past 47th fibonacci number

            if (i == 0)
            {
                return("0");        //return the first two numbers as strings
            }
            if (i == 1)
            {
                return("1");
            }

            for (int n = 2; n <= i; n++)    //fibonacci algorithm. could also use recursion if necessary
            {
                result = first + second;
                first  = second;
                second = result;
            }

            return(result.ToString()); //return the next number in the sequence as a string
        }
Exemplo n.º 23
0
        public static IEnumerable <BigInteger> Primes(BigInteger limit)
        {
            BigInteger largestPrime = _primes[_primes.Length - 1];

            for (int i = 0; i < _primes.Length; i++)
            {
                if (_primes[i] > limit)
                {
                    break;
                }

                yield return(_primes[i]);
            }

            for (BigInteger k = largestPrime + 1; k <= limit; k++)
            {
                if (IsPrime(k))
                {
                    yield return(k);
                }
            }
        }
 private RationalNumber(System.Numerics.BigInteger numerator, System.Numerics.BigInteger denominator)
 {
     System.Numerics.BigInteger g = System.Numerics.BigInteger.Abs(System.Numerics.BigInteger.GreatestCommonDivisor(numerator, denominator));
     if (numerator != 0)
     {
         if (denominator < 0)
         {
             num = -numerator / g;
             den = -denominator / g;
         }
         else
         {
             num = numerator / g;
             den = denominator / g;
         }
     }
     else
     {
         num = numerator;
         den = denominator;
     }
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        public override byte[] DecodePublicKey(byte[] pubkey, bool compress, out System.Numerics.BigInteger x, out System.Numerics.BigInteger y)
        {
            if (pubkey == null || pubkey.Length != 33 && pubkey.Length != 64 && pubkey.Length != 65)
            {
                throw new ArgumentException(nameof(pubkey));
            }

            if (pubkey.Length == 33 && pubkey[0] != 0x02 && pubkey[0] != 0x03)
            {
                throw new ArgumentException(nameof(pubkey));
            }
            if (pubkey.Length == 65 && pubkey[0] != 0x04)
            {
                throw new ArgumentException(nameof(pubkey));
            }

            byte[] fullpubkey;

            if (pubkey.Length == 64)
            {
                fullpubkey    = new byte[65];
                fullpubkey[0] = 0x04;
                Array.Copy(pubkey, 0, fullpubkey, 1, pubkey.Length);
            }
            else
            {
                fullpubkey = pubkey;
            }

            var ret = new ECPublicKeyParameters("ECDSA", _curve.Curve.DecodePoint(fullpubkey), _domain).Q;
            var x0  = ret.XCoord.ToBigInteger();
            var y0  = ret.YCoord.ToBigInteger();

            x = System.Numerics.BigInteger.Parse(x0.ToString());
            y = System.Numerics.BigInteger.Parse(y0.ToString());

            return(ret.GetEncoded(compress));
        }
Exemplo n.º 26
0
        static Tuple <bint, bint> CalcNP(bint calc, bint b, bint n, out bool res)
        {
            int powguess = (int)Math.Floor(bint.Log(calc, 2));

            powguess = Math.Min(powguess, maxexp);
            bint max2pow = bint.Pow(2, (int)powguess);

            while (max2pow * 2 <= calc)
            {
                max2pow *= 2;
                powguess++;
                if (max2pow > max2powstored)
                {
                    maxexp++;
                    max2powstored       = max2pow;
                    pow2store[powguess] = twoP(b, pow2store[powguess - 1], n, out res);
                    if (res)
                    {
                        return(pow2store[powguess]);
                    }
                }
            }
            calc -= max2pow;
            if (calc > 1)
            {
                var Q = CalcNP(calc, b, n, out res);
                if (res)
                {
                    return(new Tuple <bint, bint>(0, 0));
                }
                return(ECadd(pow2store[powguess], Q, n, out res));
            }
            else
            {
                res = false;
                return(pow2store[powguess]);
            }
        }
Exemplo n.º 27
0
        public static List <KeyValuePair <double, double> > ElgamalCipher(int p, string message)
        {
            int[] result   = new int[message.Length];
            int[] posArray = new int[message.Length];
            List <KeyValuePair <double, double> > ciph = new List <KeyValuePair <double, double> >();

            message = message.ToLower();
            for (int i = 0; i < posArray.Length; i++)
            {
                posArray[i] = alph.IndexOf(message[i]) + 1;
            }
            int f       = p - 1;
            int g       = 0;
            int counter = 2;

            while (g == 0)
            {
                System.Numerics.BigInteger t1 = System.Numerics.BigInteger.Pow(counter, f);
                if (t1 % p == 1)
                {
                    g = counter;
                }
                counter++;
            }
            Random rnd = new Random();
            //int x = rnd.Next(1, p);
            int x = 5; // зак. кл.
            int y = Convert.ToInt32(Math.Pow(g, x)) % p;

            for (int i = 0; i < posArray.Length; i++)
            {
                int k = rnd.Next(1, p - 1);
                Console.Write(k + " ");
                //int k = 7;
                ciph.Add(new KeyValuePair <double, double>(Math.Pow(g, k) % p, Math.Pow(y, k) * posArray[i] % p));
            }
            return(ciph);
        }
Exemplo n.º 28
0
        public static string Base58CheckEncode(byte[] bytes)
        {
            const string base58CheckCodeString =
                "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            var result       = string.Empty;
            var leadingZeros = 0;

            do
            {
                if (bytes[leadingZeros] == 0x00)
                {
                    ++leadingZeros;
                }
            } while (bytes[leadingZeros] == 0x00 && leadingZeros < bytes.Length);

            bytes = bytes.Reverse()
                    .Take(bytes.Length - leadingZeros)
                    .Concat(new byte[] { 0x00 })
                    .ToArray();

            var bigInteger = new System.Numerics.BigInteger(bytes);

            while (bigInteger > 0)
            {
                var remainder = bigInteger % 58;

                result    += base58CheckCodeString[(int)remainder];
                bigInteger = bigInteger / 58;
            }

            for (var i = 0; i < leadingZeros; ++i)
            {
                result += base58CheckCodeString[0];
            }

            return(new string(result.ToCharArray().Reverse().ToArray()));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Override the ReadLine method which delivers the next number (as a string) in the Fibonaci sequence.
        /// It handles the first two numbers as special cases.
        /// </summary>
        /// <returns>
        /// Returns null after the nth call else return the overriden string.
        /// </returns>
        public override string ReadLine()
        {
            // If the number of sequence is less than the max number, calculate the fibonacci number.
            if (this.NumberOfSequence < this.MaxLine)
            {
                // Case 1 where the number of sequence is 0
                if (this.NumberOfSequence == 0)
                {
                    this.firstFibNumber = 0;
                    this.NumberOfSequence++;
                    return(this.firstFibNumber.ToString());
                }

                // Case 2 where the number of sequence is 1
                else if (this.NumberOfSequence == 1)
                {
                    this.secondFibNumber = 1;
                    this.NumberOfSequence++;
                    return(this.secondFibNumber.ToString());
                }

                // Case 3 where a number is not 0 or 1
                else
                {
                    this.currentFibNumber = this.firstFibNumber + this.secondFibNumber;
                    this.firstFibNumber   = this.secondFibNumber;
                    this.secondFibNumber  = this.currentFibNumber;
                    this.NumberOfSequence++;
                    return(this.currentFibNumber.ToString());
                }
            }

            // Return null after the n-th call
            else
            {
                return(null);
            }
        }
Exemplo n.º 30
0
        public string DeployWonkaContract()
        {
            string sSenderAddress   = msSenderAddress;
            string sContractAddress = "blah";

            var account = new Account(msPassword);

            Nethereum.Web3.Web3 web3 = null;
            if ((moOrchInitData != null) && !String.IsNullOrEmpty(moOrchInitData.Web3HttpUrl))
            {
                web3 = new Nethereum.Web3.Web3(account, moOrchInitData.Web3HttpUrl);
            }
            else
            {
                web3 = new Nethereum.Web3.Web3(account);
            }

            System.Numerics.BigInteger totalSupply = System.Numerics.BigInteger.Parse("10000000");

            /**
            ** NOTE: Deployment issues have not yet been resolved - more work needs to be done
            **
            ** // System.Exception: Too many arguments: 1 > 0
            ** // at Nethereum.ABI.FunctionEncoding.ParametersEncoder.EncodeParameters (Nethereum.ABI.Model.Parameter[] parameters, System.Object[] values) [0x00078] in <b4e1e3b6a7e947da9576619c2d31bafc>:0
            ** // var receipt =
            ** // web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(msAbiWonka, msByteCodeWonka, sSenderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(900000), null, totalSupply).Result;
            ** // sContractAddress = receipt.ContractAddress;
            **
            ** // var unlockReceipt = web3.Personal.UnlockAccount.SendRequestAsync(sSenderAddress, msPassword, 120).Result;
            **
            ** // base fee exceeds gas limit?
            ** // https://gitter.im/Nethereum/Nethereum?at=5a15318e540c78242d34505f
            ** // sContractAddress = web3.Eth.DeployContract.SendRequestAsync(msAbiWonka, msByteCodeWonka, sSenderAddress, new Nethereum.Hex.HexTypes.HexBigInteger(totalSupply)).Result;
            **
            **/

            return(sContractAddress);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Bu metod verilmis a ve b ededleri ucun au+bv=1 tenlinin helli olan
        /// u ve v ededlerini hemcinin eger emsallarin ortaq boleni olarsa onda hemin
        /// bolene bolub =1 syazib hell eliyir ve o dediyim ixtisar emsalini da ucuncu element olaraq qaytarir
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        static bint[] ExtGCD(bint a, bint b)
        {
            bint x = 0;
            bint y = 1;
            bint u = 1;
            bint v = 0;

            while (b != 0)
            {
                //Console.WriteLine(a + "-" + b + "-" + " ; " + u + "-" + v);
                bint buffer = b;
                bint q      = a / b;
                b      = a % b;
                a      = buffer;
                buffer = x;
                x      = u - q * x;
                u      = buffer;
                buffer = y;
                y      = v - q * y;
                v      = buffer;
            }
            return(new bint[] { u, v, a });
        }
Exemplo n.º 32
0
        /// <summary>
        /// Generate a Fibonacci sequence, including zero as first value.
        /// </summary>
        public static BigInteger[] Fibonacci(int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            var data = new BigInteger[length];

            if (data.Length > 0)
            {
                data[0] = BigInteger.Zero;
            }
            if (data.Length > 1)
            {
                data[1] = BigInteger.One;
            }
            for (int i = 2; i < data.Length; i++)
            {
                data[i] = data[i - 1] + data[i - 2];
            }
            return(data);
        }
Exemplo n.º 33
0
        public void rsaKey(System.Numerics.BigInteger p, System.Numerics.BigInteger q)
        {
            System.Numerics.BigInteger n   = p * q;    // call n the modulus
            System.Numerics.BigInteger phi = (p - 1) * (q - 1);

            bool gcdFound = false;

            System.Numerics.BigInteger e = 2;

            while (!gcdFound)
            {
                if (gcd(e, phi) == 1)
                {
                    gcdFound = true;
                    break;
                }
                e++;
            }

            System.Numerics.BigInteger d = inverse(e, phi);

            Console.WriteLine(n + " " + e + " " + d);
        }
Exemplo n.º 34
0
        public DecimalValue(double value)
        {
            if (value == 0.0)
            {
                Exponent = 0;
                Mantissa = 0;
                return;
            }

            var decimalValue = (Decimal)value;
            int exp          = Util.BigDecimalScale(decimalValue);

            System.Numerics.BigInteger mant = Util.BigDecimalUnScaledValue(decimalValue);

            while (((mant % 10) == 0) && (mant != 0))
            {
                mant /= 10;
                exp  -= 1;
            }

            Mantissa = mant;
            Exponent = -exp;
        }
Exemplo n.º 35
0
        public static int GetBitCount(this BigInt self)
        {
            if (self.IsZero)
            {
                return(1);
            }
            byte[] bytes = BigInt.Abs(self).ToByteArray();

            int index = bytes.Length;

            while (bytes[--index] == 0)
            {
                ;
            }

            int count = index * 8;

            for (int hiByte = bytes[index]; hiByte > 0; hiByte >>= 1)
            {
                count++;
            }
            return(count);
        }
Exemplo n.º 36
0
 public static System.Numerics.BigInteger BigInteger(this JToken tk, System.Numerics.BigInteger def)
 {
     if (tk == null)
     {
         return(def);
     }
     else if (tk.TokenType == JToken.TType.ULong)
     {
         return((ulong)tk.Value);
     }
     else if (tk.IsLong && (long)tk.Value >= 0)
     {
         return((ulong)(long)tk.Value);
     }
     else if (tk.TokenType == JToken.TType.BigInt)
     {
         return((System.Numerics.BigInteger)tk.Value);
     }
     else
     {
         return(def);
     }
 }
        ///// <summary>
        ///// 动物升级消耗基数
        ///// </summary>
        ///// <param name="littleZooID">动物栏ID</param>
        ///// <param name="level">初始基数</param>
        ///// <returns></returns>
        //public static System.Numerics.BigInteger GetUpGradeBaseConsumption(int littleZooID,int level)
        //{
        //    //         Y=basenumber^(lv-1)+1
        //    var basenumber = Config.buildupConfig.getInstace().getCell(littleZooID).basenumber;

        //    var computePowFloatToBigInteger = PlayerDataModule.GetComputePowFloatToBigInteger(basenumber,level-1);
        //    var number = computePowFloatToBigInteger.str_numerator / computePowFloatToBigInteger.str_denominator + 1;

        //    return number;
        //}


        /// <summary>
        /// 动物栏门票价格升级消耗
        /// </summary>
        /// <param name="littleZooID"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public static System.Numerics.BigInteger GetUpGradeConsumption(int littleZooID, int level)
        {   /*  Y=castbase*动物消耗基数【动物栏门票期望等级】*加成预期【动物栏门票期望等级】*0.7 + lv    */
            int isLevel = level;
            var str     = Config.buildupConfig.getInstace().getCell(littleZooID).castbase;

            System.Numerics.BigInteger allbase = System.Numerics.BigInteger.Parse(str);
            int sceneID = Config.buildupConfig.getInstace().getCell(littleZooID).scene;

            var expectLevel = GetUpLittleZooPriceExpectLevel(littleZooID, level);

            var basenumber = Config.buildupConfig.getInstace().getCell(littleZooID).basenumber;
            var computePowFloatToBigInteger = PlayerDataModule.GetComputePowFloatToBigInteger(basenumber, level - 1);

            //System.Numerics.BigInteger upGradeBaseConsumption = GetUpGradeBaseConsumption(littleZooID, level);

            float additionExpect = PlayerDataModule.GetAdditionExpect(sceneID, expectLevel);
            int   number1        = (int)((additionExpect * 0.7f) * 100);

            System.Numerics.BigInteger price = computePowFloatToBigInteger.str_numerator * allbase * number1 / (computePowFloatToBigInteger.str_denominator * 100);
            //LogWarp.LogErrorFormat("测试:动物栏={0} 期望等级={1},depbase ={2},底={3},加成预期={4},分子={5},",
            //                              littleZooID, expectLevel, allbase, basenumber, additionExpect, computePowFloatToBigInteger.str_numerator);
            return(price + level);
        }
Exemplo n.º 38
0
        public void LongCtorRoundTrip()
        {
            long[] values =
            {
                0L, long.MinValue, long.MaxValue, -1, 1L + int.MaxValue, -1L + int.MinValue, 0x1234, 0xFFFFFFFFL,
                0x1FFFFFFFFL, -0xFFFFFFFFL, -0x1FFFFFFFFL, 0x100000000L, -0x100000000L, 0x100000001L, -0x100000001L,
                4294967295L, -4294967295L, 4294967296L, -4294967296L
            };

            foreach (var val in values)
            {
                try
                {
                    var a = new BigInteger(val);
                    var b = new BigInteger(a.ToByteArray());

                    Assert.AreEqual(val, (long) a, "#a_" + val);
                    Assert.AreEqual(val, (long) b, "#b_" + val);
                    Assert.AreEqual(a, b, "#a  == #b (" + val + ")");
                }
                catch (Exception e)
                {
                    Assert.Fail("Failed to roundtrip {0}: {1}", val, e);
                }
            }
        }
Exemplo n.º 39
0
        public BIM Floor(BIM? minimum, BIM? maximum)
        {
            BIM n = this.mantissa;

              if (this.exponent >= 0) {
            int e = this.exponent;
            while (e > 0 && (minimum == null || minimum <= n) && (maximum == null || n <= maximum)) {
              n = n * ten;
              e = e - 1;
            }
              }
              else {
            int e = -this.exponent;
            while (e > 0 && !n.IsZero) {
              n = n / ten;
              e = e - 1;
            }
              }

              if (minimum != null && n < minimum)
            return (BIM)minimum;
              else if (maximum != null && maximum < n)
            return (BIM)maximum;
              else
            return n;
        }
Exemplo n.º 40
0
 /** Find matching function definition for a function name and parameter
  *  value. The first definition is returned where (a) the name matches
  *  and (b) the formal parameter agrees if it is defined as constant.
  */
 private CommonTree findFunction(string name, BigInteger paramValue)
 {
     foreach (CommonTree f in functionDefinitions)
     {
         // Expected tree for f: ^(FUNC ID (ID | INT) expr)
         if (f.GetChild(0).Text.Equals(name))
         {
             // Check whether parameter matches
             CommonTree formalPar = (CommonTree)f.GetChild(1);
             if (formalPar.Token.Type == INT
                 && !BigInteger.Parse(formalPar.Token.Text).Equals(paramValue))
             {
                 // Constant in formalPar list does not match actual value -> no match.
                 continue;
             }
             // Parameter (value for INT formal arg) as well as fct name agrees!
             return f;
         }
     }
     return null;
 }
Exemplo n.º 41
0
        public void TestEquals()
        {
            var a = new BigInteger(10);
            var b = new BigInteger(10);
            var c = new BigInteger(-10);

            Assert.AreEqual(a, b, "#1");
            Assert.AreNotEqual(a, c, "#2");
            Assert.AreEqual(a, 10, "#3");
        }
Exemplo n.º 42
0
        public void IntCtorRoundTrip()
        {
            int[] values =
            {
                int.MinValue, -0x2F33BB, -0x1F33, -0x33, 0, 0x33,
                0x80, 0x8190, 0xFF0011, 0x1234, 0x11BB99, 0x44BB22CC,
                int.MaxValue
            };

            foreach (var val in values)
            {
                var a = new BigInteger(val);
                var b = new BigInteger(a.ToByteArray());

                Assert.AreEqual(val, (int)a, "#a_" + val);
                Assert.AreEqual(val, (int)b, "#b_" + val);
            }
        }
Exemplo n.º 43
0
        public static BigInt Random(this Random generator, BigInt limit) {
            ContractUtils.Requires(limit.Sign > 0, "limit");
            ContractUtils.RequiresNotNull(generator, "generator");

            BigInt res = BigInt.Zero;

            while (true) {
                // if we've run out of significant digits, we can return the total
                if (limit == BigInt.Zero) {
                    return res;
                }

                // if we're small enough to fit in an int, do so
                int iLimit;
                if (limit.AsInt32(out iLimit)) {
                    return res + generator.Next(iLimit);
                }

                // get the 3 or 4 uppermost bytes that fit into an int
                int hiData;
                byte[] data = limit.ToByteArray();
                int index = data.Length;
                while (data[--index] == 0) ;
                if (data[index] < 0x80) {
                    hiData = data[index] << 24;
                    data[index--] = (byte)0;
                } else {
                    hiData = 0;
                }
                hiData |= data[index] << 16;
                data[index--] = (byte)0;
                hiData |= data[index] << 8;
                data[index--] = (byte)0;
                hiData |= data[index];
                data[index--] = (byte)0;

                // get a uniform random number for the uppermost portion of the bigint
                byte[] randomData = new byte[index + 2];
                generator.NextBytes(randomData);
                randomData[index + 1] = (byte)0;
                res += new BigInt(randomData);
                res += (BigInt)generator.Next(hiData) << ((index + 1) * 8);

                // sum it with a uniform random number for the remainder of the bigint
                limit = new BigInt(data);
            }
        }
Exemplo n.º 44
0
 public static BigInt ModPow(this BigInt self, BigInt power, BigInt mod) {
     return BigInt.ModPow(self, power, mod);
 }
Exemplo n.º 45
0
        public void CompareOps()
        {
            long[] values = { -100000000000L, -1000, -1, 0, 1, 1000, 100000000000L };

            for (var i = 0; i < values.Length; ++i)
            {
                for (var 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);
                }
            }
        }
Exemplo n.º 46
0
        public void TestDec()
        {
            long[] values = { -100000000000L, -1000, -1, 0, 1, 1000, 100000000000L };

            for (var i = 0; i < values.Length; ++i)
            {
                var a = new BigInteger(values[i]);
                var b = --a;

                Assert.AreEqual(--values[i], (long) b, "#_" + i);
            }
        }
Exemplo n.º 47
0
        public void CompareLong()
        {
            long[] values = { -100000000000L, -1000, -1, 0, 1, 1000, 9999999, 100000000000L, 0xAA00000000, long.MaxValue, long.MinValue };

            for (var i = 0; i < values.Length; ++i)
            {
                for (var j = 0; j < values.Length; ++j)
                {
                    var a = new BigInteger(values[i]);
                    var b = values[j];
                    var c = new BigInteger(b);

                    Assert.AreEqual(a.CompareTo(c), a.CompareTo(b), "#a_" + i + "_" + j);

                    Assert.AreEqual(a > c, a > b, "#b_" + i + "_" + j);
                    Assert.AreEqual(a < c, a < b, "#c_" + i + "_" + j);
                    Assert.AreEqual(a <= c, a <= b, "#d_" + i + "_" + j);
                    Assert.AreEqual(a == c, a == b, "#e_" + i + "_" + j);
                    Assert.AreEqual(a != c, a != b, "#f_" + i + "_" + j);
                    Assert.AreEqual(a >= c, a >= b, "#g_" + i + "_" + j);

                    Assert.AreEqual(c > a, b > a, "#ib_" + i + "_" + j);
                    Assert.AreEqual(c < a, b < a, "#ic_" + i + "_" + j);
                    Assert.AreEqual(c <= a, b <= a, "#id_" + i + "_" + j);
                    Assert.AreEqual(c == a, b == a, "#ie_" + i + "_" + j);
                    Assert.AreEqual(c != a, b != a, "#if_" + i + "_" + j);
                    Assert.AreEqual(c >= a, b >= a, "#ig_" + i + "_" + j);
                }
            }
        }
Exemplo n.º 48
0
 internal override void SetCurrentAndIncrement(object value) {
     System.Numerics.BigInteger v = (System.Numerics.BigInteger)value;
     if (this.BoundaryCheck(v)) {
         this.current = v + this.step;
     }
 }
Exemplo n.º 49
0
 internal override void SetCurrent(object value, IFormatProvider formatProvider) {
     this.current = BigIntegerStorage.ConvertToBigInteger(value, formatProvider);
 }
Exemplo n.º 50
0
 internal override void MoveAfter() {
     this.current = checked(this.current + this.step);
 }
Exemplo n.º 51
0
        private static byte GetHighestByte(BigInt self, out int index, out byte[] byteArray) {
            byte[] bytes = BigInt.Abs(self).ToByteArray();
            if (self.IsZero) {
                byteArray = bytes;
                index = 0;
                return 1;
            }

            int hi = bytes.Length;
            byte b;
            do {
                b = bytes[--hi];
            } while (b == 0);
            index = hi;
            byteArray = bytes;
            return b;
        }
Exemplo n.º 52
0
 public void CompareTo()
 {
     var a = new BigInteger(99);
     Assert.AreEqual(-1, a.CompareTo(100), "#1");
     Assert.AreEqual(1, a.CompareTo(null), "#2");
 }
Exemplo n.º 53
0
        public static int BitLength(BigInt x) {
            if (x.IsZero) {
                return 0;
            }

            byte[] bytes = BigInt.Abs(x).ToByteArray();
            int index = bytes.Length;
            while (bytes[--index] == 0) ;

            return index * 8 + BitLength((int)bytes[index]);
        }
Exemplo n.º 54
0
        private Expr _Canonicalize(CompositeExpr e)
        {
            if (IsNum(e))
                return Num(e);
            List<Expr> termList = new List<Expr>();
            if (head(e) == WKSID.times)
                termList = flattenMults(e as CompositeExpr); // don't canonicalize args to preserve factors
            else if (head(e) == WKSID.plus)
            {
                bool recurse = false;
                foreach (Expr term in e.Args)
                { // flatten out all additions
                    if (head(term) == WKSID.plus)
                    {
                        foreach (Expr t in Args(term))
                        {
                            termList.Add(t);
                            recurse = true;
                        }
                    }
                    else
                    {
                        Expr canon = Canonicalize(term);
                        if (canon != term)
                            recurse = true;
                        termList.Add(canon);
                    }
                }
                if (recurse)
                    return Canonicalize(Plus(termList.ToArray()));
            }
            else foreach (Expr term in e.Args)
                    termList.Add(Canonicalize(term));

            Expr[] args = termList.ToArray();
            switch (head(e))
            {
                case WKSID.times: Expr r = CanonicalizeTimes(Mult(args));
                    if (head(r) == WKSID.times)
                    { // after simplifying, we now want to canonicalize any remaining terms to see if we can simplify further
                        termList.Clear();
                        foreach (Expr term in Args(r))
                            termList.Add(Canonicalize(term));
                        r = CanonicalizeTimes(Mult(termList.ToArray()));
                    }
                    else
                        r = Canonicalize(r);
                    return r;
                case WKSID.minus:
                    if (head(args[0]) == WKSID.minus)
                        return args[0]; // convert - - (expr) to (expr)
                    if (args[0] is IntegerNumber && (int)args[0] < 0)
                        return -(int)args[0];
                    return Canonicalize(Mult((Expr)(-1), args[0]));
                case WKSID.divide:
                    if (head(args[0]) == WKSID.power)
                        return Power(Ag(args[0], 0), Canonicalize(Mult(Ag(args[0], 1), -1)));
                    else return Power(args[0], -1);
                case WKSID.power:
                    if (args[0] == WellKnownSym.i)
                    {
                        if (IsNum(args[1]))
                        {
                            Expr n = Num(args[1]);
                            if (n is IntegerNumber)
                            {
                                if ((int)((n as IntegerNumber).Num + 2) / 4.0 == (int)((n as IntegerNumber).Num + 2) / 4)
                                    return -1;
                                if ((int)((n as IntegerNumber).Num + 1) / 4.0 == (int)((n as IntegerNumber).Num + 1) / 4)
                                    return new ComplexNumber(0, new IntegerNumber(-1));
                                if ((int)(n as IntegerNumber).Num / 4.0 == (int)(n as IntegerNumber).Num / 4)
                                    return 1;
                                return new ComplexNumber(0, new IntegerNumber(1));
                            }
                        }
                    }
                    if (args[0] == WellKnownSym.e && head(args[1]) == WKSID.ln)
                        return Ag(args[1], 0);
                    if (head(args[0]) == WKSID.power && (
                        (args[1] is IntegerNumber) ||
                        (head(Ag(args[0], 1)) == WKSID.divide && head(args[1]) == WKSID.divide))) // can't
                        return Canonicalize(Power(Ag(args[0], 0), Canonicalize(Mult(Ag(args[0], 1), args[1]))));
                    IntegerNumber qex1 = null;
                    if (IsNum(args[1]))
                    { // simplify ^0 && ^
                        Expr qex = Num(args[1]);
                        if (qex is IntegerNumber)
                        {
                            qex1 = (qex as IntegerNumber);
                            if (qex1.Num == 1)
                                return args[0];
                            else if (qex1.Num == 0)
                                return 1;
                        }
                    }
                    IntegerNumber qex0 = null;
                    if (IsNum(args[0]))
                    { // simplify 0^ && 1^
                        Expr qex = Num(args[0]);
                        if (qex is IntegerNumber)
                        {
                            qex0 = (qex as IntegerNumber);
                            if (qex0.Num == 0)
                                return 0;
                            if (qex0.Num == 1)
                                return 1;
                        }
                    }
                    if (qex0 != null && qex1 != null && qex1.Num >= 0)
                        return new BigInt(FSBigInt.Pow(qex0.Num.Num, (int)qex1.Num.Num));
                    if (head(args[0]) == WKSID.times)
                    { // expand (ab)^x  to a^x b^x
                        List<Expr> tterms = new List<Expr>();
                        foreach (Expr t in Args(args[0]))
                            tterms.Add(Canonicalize(Power(t, args[1])));
                        return Canonicalize(Mult(tterms.ToArray()));
                    }
                    return new CompositeExpr(WellKnownSym.power, args);
                case WKSID.root:
                    return Canonicalize(Power(args[1], Divide(args[0])));
                case WKSID.cos:
                    {
                        Expr val = args[0];
                        if (head(val) == WKSID.times && Ag(val, 1) == _degree && Ag(val, 0) is IntegerNumber)
                        {
                            int n = (int)Ag(val, 0);
                            if ((double)(n - 90) / 180 == (n - 90) / 180)
                                return 0;
                            if ((double)n / 360 == n / 360)
                                return 1;
                            if ((double)(n - 180) / 360 == (n - 180) / 360)
                                return -1;
                            if ((double)(n - 60) / 360 == (n - 60) / 360)
                                return Mult(1, Divide(2));
                            if ((double)(n - 120) / 360 == (n - 120) / 360)
                                return Mult(-1, Divide(2));
                            if ((double)(n - 240) / 360 == (n - 240) / 360)
                                return Mult(-1, Divide(2));
                            if ((double)(n - 300) / 360 == (n - 300) / 360)
                                return Mult(1, Divide(2));
                        }
                        if (val == WellKnownSym.pi) // cos(pi) ->  -1
                            return -1;
                        if (val == Mult(Divide(2), WellKnownSym.pi)) // cos(pi/2) -> 0
                            return 0;
                        if (head(val) == WKSID.times && Ag(val, 1) == WellKnownSym.pi)
                        { // cos(x * pi) ...
                            Expr m = Ag(val, 0);
                            int mval = (int)m;
                            if (m is IntegerNumber)                                     // cos(int * pi) ...
                                if (mval / 2.0 == mval / 2)                                 // cos(evenInt *pi)-> 1
                                    return 1;
                                else return -1;                      // cos(oddInt *pi) -> -1
                            if (head(m) == WKSID.times && (Ag(m, 0) is IntegerNumber) && Ag(m, 1) == Divide(2))
                            {  // cos(int *pi / 2) -> 0
                                return 0;
                            }
                            if (head(m) == WKSID.times && (Ag(m, 0) is IntegerNumber) && Ag(m, 1) == Divide(3))
                            { // sin(int *pi / 2) ...
                                int n = (int)Ag(m, 0);
                                if ((n - 1) / 3.0 == (n - 1) / 3 || ((n - 5) / 3.0 == (n - 5) / 3))
                                    return Mult(1, Divide(2));
                                if ((n - 2) / 3.0 == (n - 2) / 3 || ((n - 4) / 3.0 == (n - 4) / 3))
                                    return Mult(-1, Divide(2));
                            }
                        }
                        break;
                    }
                case WKSID.ln:
                    {
                        if (args[0] == WellKnownSym.e)
                            return 1;
                        break;
                    }
                case WKSID.tan:
                    {
                        Expr val = args[0];
                        if (head(val) == WKSID.times && Ag(val, 1) == _degree)
                            return Canonicalize(new CompositeExpr(WellKnownSym.tan, Mult(WellKnownSym.pi, Num(Mult(Ag(val, 0), Divide(180))))));
                        break;
                    }
                case WKSID.index:
                    {
                        Expr[] canoned = Array.ConvertAll<Expr, Expr>(args, Canonicalize);
                        return new CompositeExpr(WellKnownSym.index, canoned);
                    }
                case WKSID.sin:
                    {
                        Expr val = args[0];
                        if (head(val) == WKSID.times && Ag(val, 1) == _degree && Ag(val, 0) is IntegerNumber)
                        {
                            int n = (int)Ag(val, 0);
                            if ((double)n / 180 == n / 180)
                                return 0;
                            if ((double)(n - 90) / 360 == (n - 90) / 360)
                                return 1;
                            if ((double)(n + 90) / 360 == (n + 90) / 360)
                                return -1;
                            if ((double)(n - 30) / 360 == (n - 30) / 360)
                                return Mult(1, Divide(2));
                            if ((double)(n - 150) / 360 == (n - 150) / 360)
                                return Mult(1, Divide(2));
                            if ((double)(n - 210) / 360 == (n - 210) / 360)
                                return Mult(-1, Divide(2));
                            if ((double)(n - 330) / 360 == (n - 330) / 360)
                                return Mult(-1, Divide(2));
                        }
                        if (head(val) == WKSID.times && Ag(val, 1) == _degree)
                            return Canonicalize(new CompositeExpr(WellKnownSym.sin, Mult(WellKnownSym.pi, Num(Mult(Ag(val, 0), Divide(180))))));
                        if (val == WellKnownSym.pi) //sin(pi)  -> 0
                            return 0;
                        if (val == Mult(Divide(2), WellKnownSym.pi)) // sin(pi/2) -> 1
                            return 1;
                        if (head(val) == WKSID.times && Ag(val, 1) == WellKnownSym.pi)
                        { // sin(x * pi) ...
                            Expr m = Ag(val, 0);
                            if (m is IntegerNumber)                                     // sin(int * pi) -> 0
                                return 0;
                            if (head(m) == WKSID.times && (Ag(m, 0) is IntegerNumber) && Ag(m, 1) == Divide(2))
                            { // sin(int *pi / 2) ...
                                int n = (int)Ag(m, 0);
                                if ((n - 1) / 4.0 == (n - 1) / 4)
                                    return 1;                // sin(1, 5, 9...*pi/2) -> 1
                                else return -1;              // sin(3, 7, 11 ...*pi/2) -> -1
                            }
                            if (head(m) == WKSID.times && (Ag(m, 0) is IntegerNumber) && Ag(m, 1) == Divide(6))
                            { // sin(int *pi / 2) ...
                                int n = (int)Ag(m, 0);
                                if ((n - 1) / 6.0 == (n - 1) / 6 || ((n - 5) / 6.0 == (n - 5) / 6))
                                    return Mult(1, Divide(2));
                                if ((n - 7) / 6.0 == (n - 7) / 6 || ((n - 11) / 6.0 == (n - 11) / 6))
                                    return Mult(-1, Divide(2));
                            }
                        }
                        break;
                    }
                case WKSID.plus:
                    Hashtable terms = new Hashtable();
                    foreach (Expr t in args)
                    {
                        if (t is ComplexNumber)
                        {
                            if (terms.Contains("unitless"))
                                terms["unitless"] = Num(Plus((Expr)terms["unitless"], (t as ComplexNumber).Re));
                            else terms.Add("unitless", (t as ComplexNumber).Re);
                        }
                        if (IsNum(t))
                        {
                            if (terms.Contains("unitless"))
                                terms["unitless"] = Num(Plus((Expr)terms["unitless"], t));
                            else terms.Add("unitless", Num(t));
                        }
                        else if (t is LetterSym || t is WellKnownSym || head(t) == WKSID.plusminus)
                        {
                            if (terms.Contains(t))
                                terms[t] = Canonicalize(Plus((Expr)terms[t], 1));
                            else terms.Add(t, (Expr)1);
                        }
                        else if (t is ArrayExpr)
                        {
                            terms.Add(t, (Expr)1);
                        }
                        else
                        {
                            Expr swVal = t is ComplexNumber ? Mult((t as ComplexNumber).Im, WellKnownSym.i) : t;
                            switch (head(swVal))
                            {
                                case WKSID.times:
                                    List<Expr> syms = new List<Expr>();
                                    List<Expr> nums = new List<Expr>();
                                    foreach (Expr tt in Args(swVal))
                                        if (IsNum(tt))
                                            nums.Add(tt);
                                        else syms.Add(tt);
                                    Expr baseTerm = syms.Count == 1 ? syms[0] : Mult(syms.ToArray());
                                    Expr baseNum = 1;
                                    if (nums.Count == 1)
                                        baseNum = nums[0];
                                    else if (nums.Count > 1)
                                        baseNum = Num(Mult(nums.ToArray()));
                                    if (terms.Contains(baseTerm))
                                        terms[baseTerm] = Canonicalize(Plus((Expr)terms[baseTerm], baseNum));
                                    else terms.Add(baseTerm, baseNum);
                                    break;
                                case WKSID.magnitude:
                                case WKSID.factorial:
                                case WKSID.summation:
                                case WKSID.power:
                                    if (terms.Contains(swVal))
                                        terms[swVal] = Canonicalize(Plus((Expr)terms[swVal], 1));
                                    else terms.Add(swVal, (Expr)1);
                                    break;
                            }
                        }
                    }

                    List<Expr> plTerms = new List<Expr>();
                    List<Expr> plNumTerms = new List<Expr>();
                    foreach (DictionaryEntry de in terms)
                    {
                        if (de.Key is string && (string)de.Key == "unitless")
                        {
                            if (!(de.Value is IntegerNumber) || (int)(Expr)de.Value != 0)
                                plNumTerms.Add((Expr)de.Value);
                        }
                        else
                        {
                            Expr baseCount = (de.Value as Expr);
                            if (baseCount is IntegerNumber && (int)baseCount == 0)
                                continue;
                            if (baseCount is IntegerNumber && (int)baseCount == 1)
                                plTerms.Add((Expr)de.Key);
                            else plTerms.Add(Mult((Expr)de.Value, (Expr)de.Key));
                        }
                    }
                    Expr plNum = null;
                    if (plNumTerms.Count == 1)
                        plNum = plNumTerms[0];
                    else if (plNumTerms.Count > 1)
                        plNum = Num(Plus(plNumTerms.ToArray()));
                    if (plNum != null)
                        plTerms.Add(plNum);
                    if (plTerms.Count == 0)
                        return 0;
                    else if (plTerms.Count == 1)
                        return plTerms[0];
                    else return Plus(plTerms.ToArray());
                case WKSID.floor:
                    if (args.Length == 1)
                    {
                        if (args[0] is IntegerNumber) return args[0];
                        else if (args[0] is RationalNumber)
                        {
                            RationalNumber rn = (RationalNumber)args[0];
                            var divmod = new FSBigInt();
                            FSBigInt q = FSBigInt.DivRem(rn.Num.Num.Num, rn.Num.Denom.Num, out divmod);
                            FSBigInt qq = q, rr = divmod;
                            return new BigInt(qq - (qq.Sign * rr.Sign == -1 ? FSBigInt.One : FSBigInt.Zero));
                        }
                        else if (args[0] is DoubleNumber)
                        {
                            DoubleNumber dn = (DoubleNumber)args[0];
                            return Math.Floor(dn.Num);
                        }
                    }
                    break;
                case WKSID.magnitude:
                    if (args.Length == 1)
                    {
                        if (args[0] is IntegerNumber) return (args[0] as IntegerNumber).Num.abs();
                        else if (args[0] is DoubleNumber) return Math.Abs(((DoubleNumber)args[0]).Num);
                        else return new CompositeExpr(WellKnownSym.magnitude, args);
                    }
                    break;
                case WKSID.ceiling:
                    if (args.Length == 1)
                    {
                        if (args[0] is IntegerNumber) return args[0];
                        else if (args[0] is RationalNumber)
                        {
                            RationalNumber rn = (RationalNumber)args[0];
                            FSBigInt divmod = new FSBigInt();
                            FSBigInt q = FSBigInt.DivRem(rn.Num.Num.Num, rn.Num.Denom.Num, out divmod);
                            FSBigInt qq = q, rr = divmod;
                            return new BigInt(qq + (qq.Sign * rr.Sign == 1 ? FSBigInt.One : FSBigInt.Zero));
                        }
                        else if (args[0] is DoubleNumber)
                        {
                            DoubleNumber dn = (DoubleNumber)args[0];
                            return Math.Floor(dn.Num);
                        }
                    }
                    break;
            }
            return new CompositeExpr(Canonicalize(e.Head), args);
        }
Exemplo n.º 55
0
        public void Ctor_ByteArray_ShouldThrowArgumentNullExceptionWhenValueIsNull()
        {
            const byte[] value = null;

            try
            {
                var actual = new BigInteger(value);
                Assert.Fail("#1:" + actual);
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsNull(ex.InnerException);
                Assert.AreEqual("value", ex.ParamName);
            }
        }
Exemplo n.º 56
0
        public void TestIntCtorProperties()
        {
            BigInteger a = new BigInteger(10);
            Assert.IsTrue(a.IsEven, "#1");
            Assert.IsFalse(a.IsOne, "#2");
            Assert.IsFalse(a.IsPowerOfTwo, "#3");
            Assert.IsFalse(a.IsZero, "#4");
            Assert.AreEqual(1, a.Sign, "#5");

            Assert.IsFalse(new BigInteger(11).IsEven, "#6");
            Assert.IsTrue(new BigInteger(1).IsOne, "#7");
            Assert.IsTrue(new BigInteger(32).IsPowerOfTwo, "#8");
            Assert.IsTrue(new BigInteger(0).IsZero, "#9");
            Assert.IsTrue(new BigInteger().IsZero, "#9b");
            Assert.AreEqual(0, new BigInteger(0).Sign, "#10");
            Assert.AreEqual(-1, new BigInteger(-99999).Sign, "#11");

            Assert.IsFalse(new BigInteger(0).IsPowerOfTwo, "#12");
            Assert.IsFalse(new BigInteger().IsPowerOfTwo, "#12b");
            Assert.IsFalse(new BigInteger(-16).IsPowerOfTwo, "#13");
            Assert.IsTrue(new BigInteger(1).IsPowerOfTwo, "#14");
        }
Exemplo n.º 57
0
        public void CompareOps2()
        {
            var a = new BigInteger(100000000000L);
            var b = new BigInteger(28282828282UL);

            Assert.IsTrue(a >= b, "#1");
            Assert.IsTrue(a >= b, "#2");
            Assert.IsFalse(a < b, "#3");
            Assert.IsFalse(a <= b, "#4");
            Assert.AreEqual(1, a.CompareTo(b), "#5");
        }
Exemplo n.º 58
0
        public void TestBitwiseOps()
        {
            long[] values = { -100000000000L, -1000, -1, 0, 1, 1000, 100000000000L, 0xFFFF00000000L };

            for (var i = 0; i < values.Length; ++i)
            {
                for (var j = 0; j < values.Length; ++j)
                {
                    var a = new BigInteger(values[i]);
                    var b = new BigInteger(values[j]);

                    Assert.AreEqual(values[i] | values[j], (long) (a | b), "#b_" + i + "_" + j);
                    Assert.AreEqual(values[i] & values[j], (long) (a & b), "#a_" + i + "_" + j);
                    Assert.AreEqual(values[i] ^ values[j], (long) (a ^ b), "#c_" + i + "_" + j);
                    Assert.AreEqual(~values[i], (long) ~a, "#d_" + i + "_" + j);
                }
            }
        }
Exemplo n.º 59
0
			/// <summary>
			/// creates a timestamp out of fps value
			/// </summary>
			/// <param name="rate">fpsnum</param>
			/// <param name="scale">fpsden</param>
			/// <param name="pos">frame position</param>
			/// <returns>timestamp in nanoseconds</returns>
			static UInt64 timestampcalc(int rate, int scale, UInt64 pos)
			{
				// rate/scale events per second
				// timestamp is in nanoseconds
				// round down, consistent with JPC-rr apparently?
				var b = new System.Numerics.BigInteger(pos) * scale * 1000000000 / rate;

				return (UInt64)b;
			}
Exemplo n.º 60
0
        public static bool Prod()
        {
            bool result = false;
            Parser p = new Parser();
            Header h = p.Parse();
            string signData = string.Empty;

            using (StringWriter sw = new StringWriter(new System.Text.StringBuilder()))
            {
                foreach (SignedHeader sh in h.headers)
                {
                    sw.WriteLine(string.Concat(sh.name, ":", sh.value));
                }

                sw.Write(h.ValueForSigning());
                signData = sw.GetStringBuilder().ToString();
            }

            byte[] signBytes = System.Text.Encoding.UTF8.GetBytes(signData);

            var hashy = new SHA1Managed();
            byte[] hashedBytes = hashy.ComputeHash(signBytes);

            AsymetricEncryption pubAsym = new AsymetricEncryption();
            string pe = "AQAB";
            //string modulus = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH1LXIAg+RF5u2/GZ0Ic1cdsuH9JH+S5l3Ey6nTPk4zpC708cANgcz06OUIgrl5Kipeu5xLFoqZtGpsi6nGgVuqetwAnNcIwyMPRHf7emIIgixj56lXkMglhfUkmEEzeXmM16Zr65rgZ3FTewbbC6v/kkP29i2Yq2Xk6iWJM5PmwIDAQAB";
            string modulus = "2JMzkmcqysCLK1oaIAtwBkIEo9xqOycpQcPBIq+nbWkvbkjvShE+RfsJ2ukRtCa0XBv5sBTaEtFuBy4Nq6ip2VIrqESmcJxgL2hdtbOWcnTbipIvPhd//HFydJdTbBCOy6wZHk81WoZkaitJqjMkKDrTKpCp21NW1QAvuJ6Xp68=";
            byte[] peBytes = Convert.FromBase64String(pe);
            byte[] modBytes = Convert.FromBase64String(modulus);
            System.Numerics.BigInteger peInt = new System.Numerics.BigInteger(peBytes);
            System.Numerics.BigInteger moInt = new System.Numerics.BigInteger(modBytes);

            RsaKeyParameters key = GetPublicKey();

            //pubAsym.PublicExponent = new System.Numerics.BigInteger(key.Exponent.ToByteArray());
            //pubAsym.Modulous = new System.Numerics.BigInteger(key.Modulus.ToByteArray());
            pubAsym.PublicExponent = new System.Numerics.BigInteger(peBytes);
            pubAsym.Modulous = new System.Numerics.BigInteger(modBytes);

            byte[] publicBytes = pubAsym.PublicSign(hashedBytes);
            byte[] signature = Convert.FromBase64String(h.signature);

            result = signature.SequenceEqual(publicBytes);

            return result;
        }