예제 #1
0
        public void FormatE1()
        {
            var first = new BigInteger(123456789);
            Assert.AreEqual(first.ToString("E", CultureInfo.InvariantCulture), "1.234568E+008");
            Assert.AreEqual(first.ToString("e", CultureInfo.InvariantCulture), "1.234568e+008");

            Debug.Print("BigInteger Format First ok");

            var second = BigInteger.Parse("10000009000000001", CultureInfo.InvariantCulture);
            Assert.AreEqual(second.ToString("E", CultureInfo.InvariantCulture), "1.000001E+016");
            Assert.AreEqual(second.ToString("e", CultureInfo.InvariantCulture), "1.000001e+016");

            Debug.Print("BigInteger Format Second ok");

            var third = BigInteger.Parse("10000005000000001", CultureInfo.InvariantCulture);
            Assert.AreEqual(third.ToString("E", CultureInfo.InvariantCulture), "1.000001E+016");
            Assert.AreEqual(third.ToString("e", CultureInfo.InvariantCulture), "1.000001e+016");

            Debug.Print("BigInteger Format Third ok");

            var fourth = BigInteger.Parse("10000004000000001", CultureInfo.InvariantCulture);
            Assert.AreEqual(fourth.ToString("E", CultureInfo.InvariantCulture), "1.000000E+016");
            Assert.AreEqual(fourth.ToString("e", CultureInfo.InvariantCulture), "1.000000e+016");

            Debug.Print("BigInteger Format Fourth ok");

            var fifth = BigInteger.Parse("10000095000000001", CultureInfo.InvariantCulture);
            Assert.AreEqual(fifth.ToString("E", CultureInfo.InvariantCulture), "1.000010E+016");
            Assert.AreEqual(fifth.ToString("e", CultureInfo.InvariantCulture), "1.000010e+016");

            Debug.Print("BigInteger Format Fifth ok");
        }
예제 #2
0
        public void FormatC()
        {
            var first = new BigInteger(123456789);
            Assert.AreEqual(first.ToString("C", CultureInfo.InvariantCulture), "¤123,456,789.00");
            Assert.AreEqual(first.ToString("c", CultureInfo.InvariantCulture), "¤123,456,789.00");
            Assert.AreEqual(first.ToString("C3", CultureInfo.InvariantCulture), "¤123,456,789.000");
            Assert.AreEqual(first.ToString("c3", CultureInfo.InvariantCulture), "¤123,456,789.000");

            Assert.AreEqual(first.ToString("C3", CultureInfo.GetCultureInfo("en-US")), "$123,456,789.000");
            Assert.AreEqual(first.ToString("c3", CultureInfo.GetCultureInfo("en-US")), "$123,456,789.000");

            Assert.AreEqual(first.ToString("C3", CultureInfo.GetCultureInfo("fr-FR")), "123\u00A0456\u00A0789,000 €");
            Assert.AreEqual(first.ToString("c3", CultureInfo.GetCultureInfo("fr-FR")), "123\u00A0456\u00A0789,000 €");

            Assert.AreEqual(first.ToString("C3", CultureInfo.GetCultureInfo("ja-JP")), "¥123,456,789.000");
            Assert.AreEqual(first.ToString("c3", CultureInfo.GetCultureInfo("ja-JP")), "¥123,456,789.000");

            var second = BigInteger.Parse("100000090000000010", CultureInfo.InvariantCulture);
            Assert.AreEqual(second.ToString("C", CultureInfo.InvariantCulture), "¤100,000,090,000,000,010.00");
            Assert.AreEqual(second.ToString("c", CultureInfo.InvariantCulture), "¤100,000,090,000,000,010.00");
            Assert.AreEqual(second.ToString("C3", CultureInfo.InvariantCulture), "¤100,000,090,000,000,010.000");
            Assert.AreEqual(second.ToString("c3", CultureInfo.InvariantCulture), "¤100,000,090,000,000,010.000");

            Assert.AreEqual(second.ToString("C3", CultureInfo.GetCultureInfo("en-US")), "$100,000,090,000,000,010.000");
            Assert.AreEqual(second.ToString("c3", CultureInfo.GetCultureInfo("en-US")), "$100,000,090,000,000,010.000");

            Assert.AreEqual(second.ToString("C3", CultureInfo.GetCultureInfo("fr-FR")), "100\u00A0000\u00A0090\u00A0000\u00A0000\u00A0010,000 €");
            Assert.AreEqual(second.ToString("c3", CultureInfo.GetCultureInfo("fr-FR")), "100\u00A0000\u00A0090\u00A0000\u00A0000\u00A0010,000 €");

            Assert.AreEqual(second.ToString("C3", CultureInfo.GetCultureInfo("ja-JP")), "¥100,000,090,000,000,010.000");
            Assert.AreEqual(second.ToString("c3", CultureInfo.GetCultureInfo("ja-JP")), "¥100,000,090,000,000,010.000");
        }
        private static void SaddyCopperOperation(BigInteger number)
        {
            if (number.ToString().Length == 1 || numberOfTransformations == 10)
            {
                if (numberOfTransformations < 10)
                {
                    Console.WriteLine(numberOfTransformations);
                }

                Console.WriteLine(number);
                return;
            }
            numberOfTransformations++;

            List<int> listOfsums = new List<int>();
            while (number > 10)
            {
                number /= 10;
                List<int> digitsAtEvenPositions = new List<int>();
                for (int i = 0; i < number.ToString().Length; i += 2)
                {
                    digitsAtEvenPositions.Add(number.ToString()[i] - '0');
                }

                listOfsums.Add(digitsAtEvenPositions.Sum());
            }
            long product = 1;
            foreach (var num in listOfsums)
            {
                product *= num;
            }
            //Console.WriteLine(product);
            //--------------------------------
            SaddyCopperOperation(product);
        }
예제 #4
0
 public string Run()
 {
     BigInteger total = new BigInteger(0);
     for (int i = 1; i <= 1000; i++)
     {
         total += BigInteger.Pow(i, i);
     }
     return total.ToString().Substring(total.ToString().Length - 10);
 }
        static void Main(string[] args)
        {
            ulong startNumber = ulong.Parse(Console.ReadLine());
            ulong endNumber = ulong.Parse(Console.ReadLine());
            string replacementString = Console.ReadLine();
            BigInteger sum = new BigInteger();

            string sumString = sum.ToString();

            //calculate sum of numbers
            for (ulong i = startNumber; i < endNumber; i++)
            {
                if (i % 5 == 0)
                {
                    sum += i;
                }
                else
                {
                    ulong mod = i % 5;
                    sum += mod;
                }
            }

            string replacedDigit;
            if (sum % 2 == 0)
            {
                for (int i = 0; i < sumString.Length; i++)
                {

                    replacedDigit = sum.ToString()[0].ToString();
                    replacedDigit = replacementString;

                    if (sumString[i].Equals(replacedDigit))
                    {
                        string newString = sumString[i].ToString();
                        newString = replacementString;
                    }
                }

            }
            else
            {
                for (int i = 0; i < sumString.Length; i++)
                {
                    replacedDigit = sum.ToString()[sum.ToString().Length - 1].ToString();
                    replacedDigit = replacementString;

                    if (sumString[i].Equals(replacedDigit))
                    {
                        string newString = sumString[i].ToString();
                        newString = replacementString;
                    }
                }
            }
            Console.WriteLine(sumString);
        }
예제 #6
0
파일: Function.cs 프로젝트: GarageInc/all
        private static bool is_prime_MR(BigInteger R, int num)
        {
            Random random = new Random();
            BigInteger s = 0;
            BigInteger t = R - 1;

            while (t % 2 == 0)
            {
                t = t / 2;
                s++;
            }

            String st = "";
            int p;
            int q = Int32.MaxValue;
            BigInteger A;
            BigInteger b;
            BigInteger i = 0;

            for (int j = 1; j <= num; j++)
            {
                p = random.Next(10);
                if (p % 2 == 0)
                    p = p + 1;
                st = p.ToString();
                while (st.Length <= R.ToString().Length - q.ToString().Length)
                {
                    st = random.Next(q) + st;
                }
                try
                {
                    st = random.Next(10 ^ (R.ToString().Length - st.Length - 2)) + st;
                }
                catch { }
                A = BigInteger.Parse(st);
                if (A.IsOne)
                    A++;
                if ((R % A).IsZero)
                    return false;
                b = BigInteger.ModPow(A, t, R);
                if (b.IsOne)
                    continue;
                i = 0;
                do
                {
                    b = BigInteger.ModPow(b, BigInteger.One + BigInteger.One, R);
                    i++;
                }
                while (!(b.IsOne || b.ToString() == (R - 1).ToString() || i > s));
                if (i > s)
                    return false;
            }

            return true;
        }
예제 #7
0
        static void Main(string[] args)
        {
            short n = 1000;
            var bi = new BigInteger();

            for (short i = 1; i <= n; i++)
                bi += Pow(i, i);

            Console.WriteLine(bi.ToString().Substring(bi.ToString().Length-10, 10));
            Console.ReadKey();
        }
예제 #8
0
 private void Calculate()
 {
     BigInteger res = new BigInteger();
     res = a + b;
     textBox3.Text = res.ToString();
     res = a * b;
     textBox4.Text = res.ToString();
     res = BigInteger.Pow(a, 2);
     textBox5.Text = res.ToString();
     res = BigInteger.ModPow(a, 1, b);
     textBox6.Text = res.ToString();
 }
예제 #9
0
 private static int[] ConvertToArray(BigInteger num)
 {
     int[] digits = new int[num.ToString().Length];
     string number = num.ToString();
     BigInteger currentNumber = num;
     for (int i = number.Length - 1; i >= 0; i--)
     {
         digits[i] = (int)(currentNumber % 10);
         currentNumber /= 10;
     }
     return digits;
 }
예제 #10
0
 // Convert number of digit to array
 static int[] ConvertToArray(BigInteger num)
 {
     string digit = num.ToString();
     int[] digits = new int[num.ToString().Length];
     int count = 0;
     foreach (var item in digit)
     {
         digits[count] = item - '0';
         count++;
     }
     return digits;
 }
        public static BigInteger CalculateProduct(BigInteger firstMultiplier, BigInteger secondMultiplier)
        {
            int n = firstMultiplier.ToString().Length;

            a = BigInteger.Parse(firstMultiplier.ToString().Substring(0, n / 2));
            b = BigInteger.Parse(firstMultiplier.ToString().Substring(n / 2));
            c = BigInteger.Parse(secondMultiplier.ToString().Substring(0, n / 2));
            d = BigInteger.Parse(secondMultiplier.ToString().Substring(n / 2));

            BigInteger ac = a * c;
            BigInteger bd = b * d;
            return BigInteger.Pow(10, n) * ac + BigInteger.Pow(10, n / 2) * ((a + b) * (c + d) - ac - bd) + bd;
        }
예제 #12
0
 static bool IsLychrel(BigInteger nn)
 {
     int attempts = 50;
     do
     {
         nn += BigInteger.Parse(Util.ReverseString(nn.ToString()));
         if (Util.IsPalindrome(nn.ToString()))
         {
             return false;
         }
     } while (attempts-- > 0);
     return true;
 }
예제 #13
0
        public void FormatD()
        {
            var first = new BigInteger(123456789);
            Assert.AreEqual(first.ToString("D", CultureInfo.InvariantCulture), "123456789");
            Assert.AreEqual(first.ToString("d", CultureInfo.InvariantCulture), "123456789");
            Assert.AreEqual(first.ToString("D20", CultureInfo.InvariantCulture), "00000000000123456789");
            Assert.AreEqual(first.ToString("d20", CultureInfo.InvariantCulture), "00000000000123456789");

            var second = BigInteger.Parse("100000090000000010", CultureInfo.InvariantCulture);
            Assert.AreEqual(second.ToString("D", CultureInfo.InvariantCulture), "100000090000000010");
            Assert.AreEqual(second.ToString("d", CultureInfo.InvariantCulture), "100000090000000010");
            Assert.AreEqual(second.ToString("D20", CultureInfo.InvariantCulture), "00100000090000000010");
            Assert.AreEqual(second.ToString("d20", CultureInfo.InvariantCulture), "00100000090000000010");
        }
예제 #14
0
        public override string GetAnswer()
        {
            BigInteger pectorial = new BigInteger(1);
            for (int i=1; i<=100; i++) {
                pectorial *= i;
            }

            int result = 0;
            foreach (char c in pectorial.ToString().ToArray()) {
                result += c - 48;
            }

            return string.Format("결과값 {0} 의 자리수를 모두 더한 값 : {1}", pectorial.ToString(), result);
        }
예제 #15
0
 public static string ShortenCurrency(this string String, BigInteger Currency)
 {
     if (Currency < 1000000) return Currency.ToString("#,##0");
     else
     {
         string currencyString = Currency.ToString();
         int currencyStringLength = currencyString.Length;
         double calculation = (currencyStringLength / 3d);
         int baseNumberLength = ((calculation == (int)calculation) ? 3 : (int)Math.Round((calculation - (int)calculation) * 3));
         string decimals = currencyString.Substring(baseNumberLength, Math.Min(3, (currencyStringLength - baseNumberLength))).TrimEnd('0');
         return String = (currencyString.Substring(0, baseNumberLength) +
            ((decimals.Length > 0) ? ("." + decimals) : null)
             + " " + CurrencyNames[(int)Math.Ceiling(calculation) - 3]);
     }
 }
예제 #16
0
        private static IEnumerable<BigInteger> EnumeratePalindromesBetween(BigInteger min, BigInteger max)
        {
            var minDigits = Math.Min(min.ToString().Length, max.ToString().Length);
            var maxDigits = Math.Max(max.ToString().Length, max.ToString().Length);

            for (var digitCount = minDigits; digitCount <= maxDigits; digitCount++)
            {
                foreach (var value in EnumerateCandidatesOfLength(digitCount))
                {
                    Debug.Assert(IsPalindrome(value));
                    if (value >= min && value <= max)
                        yield return value;
                }
            }
        }
예제 #17
0
 static bool IsTruncatable(BigInteger num)
 {
     if (IsLeftTruncatable(num.ToString()))
     {
         if(IsRightTruncatable(num.ToString()))
         {
             return true;
         }
         else
         {
             return false;
         }
     }
     return false;
 }
예제 #18
0
        static void Main(string[] args)
        {
            // Variable declarations
            var answer = new BigInteger();

            // Load data
            var names = File.ReadAllText("data.txt").Split(',').Select(name => name.Trim(new[] {'"'})).ToList();

            // Start timer
            var timer = new Stopwatch();
            timer.Start();

            // Calculations
            names.Sort();
            var position = 1;
            foreach (var name in names)
            {
                answer += position * name.Select(c => Scores[c]).Sum();
                position++;
            }

            // Cleanup
            timer.Stop();
            Console.WriteLine("Answer: {0}", answer);
            Console.WriteLine();
            Clipboard.SetText(answer.ToString());
            Console.WriteLine("Time spent: {0:0.00}s", timer.ElapsedMilliseconds / 1000.0);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
예제 #19
0
        static BigInteger calcular(BigInteger x, BigInteger y)
        {
            int n;
            int l1 = x.ToString().Length;
            int l2 = y.ToString().Length;

            if (l1 > l2)
            {
                n = l1;
            }
            else
            {
                n = l2;
            }

            if (n < 4) return x * y;

            n = ((n + 1) / 2);

            BigInteger x2 = x >> n;
            BigInteger x1 = x - (x2 << n);
            BigInteger y2 = y >> n;
            BigInteger y1 = y - (y2 << n);

            BigInteger z2 = calcular(x1, y1);
            BigInteger z0 = calcular(x2, y2);
            BigInteger z1 = calcular(x1 + x2, y1 + y2);

            return z2 + ((z1 -z2 - z0) << n) + (z0 << (2 * n));
        }
예제 #20
0
        public void Mersenne(int n)
        {
            BigInteger Pow2Sub1, rem;
            string strPow2Sub1;

            //for (int i = 0, x = 2; i < primes.Length; i++)
            int x = 2;
            Parallel.For(0, primes.Length, (int i) =>
            {
                Pow2Sub1 = new BigInteger(1) << (int)primes[i];
                Pow2Sub1 -= 1;
                //sw1.Restart();
                rem = BigInteger.ModPow(3, Pow2Sub1 - 1, Pow2Sub1);
                if (rem.IsOne)
                {
                    //sw1.Stop();
                    strPow2Sub1 = Pow2Sub1.ToString();
                    if (x < 10)
                        Console.WriteLine("M[{0}] = {1}", primes[i], strPow2Sub1);
                    else
                        Console.WriteLine("M[{0}] = {1}...{2}", primes[i], strPow2Sub1.Substring(0, 12), strPow2Sub1.Substring(strPow2Sub1.Length - 12, 12));
                    x++;
                    //Console.WriteLine("elapsed time: {0} ms\n", sw1.ElapsedMilliseconds);
                }
            });
        }
예제 #21
0
        public string ConvertHexToDec(string hex)
        {
            var result     = _hexReader.ToByteArray(hex, Endian.Big).ToArray();
            var bigInteger = new System.Numerics.BigInteger(result);

            return(bigInteger.ToString());
        }
예제 #22
0
        static void Main(string[] args)
        {
            // Variable declarations
            var answer = "";
            var sum = new BigInteger();

            // Load data
            var data = File.ReadAllLines("data.txt").Select(BigInteger.Parse).ToList();

            // Start timer
            var timer = new Stopwatch();
            timer.Start();

            // Calculations
            foreach (var i in data)
            {
                sum += i;
            }

            answer = sum.ToString().Substring(0, 10);

            // Cleanup
            timer.Stop();
            Console.WriteLine("Answer: {0}", answer);
            Console.WriteLine();
            Clipboard.SetText(answer.ToString());
            Console.WriteLine("Time spent: {0:0.00}s", timer.ElapsedMilliseconds / 1000.0);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
예제 #23
0
파일: Bank.cs 프로젝트: blacha14/nitrogen
        public virtual bool checkIfNumberIsCorrect(string cardNumber)
        {
            if (cardNumber.Length > 9)
            {
                string cardNumberType = (cardNumber.Length > 26 ? "IBAN" : "NRB");

                if (cardNumberType.Equals("NRB"))
                    cardNumber = "PL" + cardNumber;

                BigInteger test = new BigInteger();
                string sCopy = cardNumber.Substring(4, cardNumber.Length - 4) + cardNumber.Substring(0, 4);

                for (int a = 0; a <= sCopy.Length - 1; a++)
                {
                    if (sCopy[a] >= 'A' && sCopy[a] <= 'Z')
                        sCopy = sCopy.Replace(sCopy[a].ToString(), ((int)(sCopy[a]) - 55).ToString());
                    if (sCopy[a] >= 'a' && sCopy[a] <= 'z')
                        sCopy = sCopy.Replace(sCopy[a].ToString(), ((int)(sCopy[a]) - 87).ToString());
                }

                test = BigInteger.Parse(sCopy);

                test %= 97;
                return (test.ToString().Equals("1") ? true : false);
            }
            else return false;
        }
예제 #24
0
        static void Main(string[] args)
        {
            // Variable declarations
            var answer = 0L;
            var n = new BigInteger();

            // Load data

            // Start timer
            var timer = new Stopwatch();
            timer.Start();

            // Calculations
            n = EulerHelper.Factorial(100);
            answer = n.ToString().Sum(c => long.Parse(c.ToString()));

            // Cleanup
            timer.Stop();
            Console.WriteLine("Answer: {0}", answer);
            Console.WriteLine();
            Clipboard.SetText(answer.ToString());
            Console.WriteLine("Time spent: {0:0.00}s", timer.ElapsedMilliseconds / 1000.0);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
예제 #25
0
        public void Execute()
        {
            //это сам алгоритм
            _factorial = 1;
            for (int i = _number1; i < _number2 + 1; i++)
            {
                _factorial *= i;
            }

            Data = _factorial.ToString();

            if (/*_myClientNumber < _highestClientNumber &&*/ _myClientNumber != 0)
            {
                var incomingPackage = _internalPackageProvider.GetPackage();
                var firstMult = BigInteger.Parse(incomingPackage.Data);
                _factorial *= firstMult;
            }
            if (_myClientNumber < _highestClientNumber)
            {
                formPackage(_factorial.ToString(),_myClientNumber+1);
                OnSend();
            }

            if (_myClientNumber == _highestClientNumber)
            {
                formPackage(_factorial.ToString(), -1);
                OnReady();
            }
        }
예제 #26
0
        public static bool isNivenNumber(BigInteger num, String nivenString = "")
        {
            bool lookup;
            if (NN_dic.TryGetValue(num, out lookup))
                return lookup;

            // Hashad Number, aka Niven Number
            // #387
            if (nivenString.Length == 0)
            {
                nivenString = num.ToString();
            }
            BigInteger counter = 0;
            if (num <= 0)
            {
                NN_dic[num] = false;
                return false;
            }
            foreach (var item in nivenString)
            {
                counter += int.Parse(item.ToString());
            }
            if (num % counter == 0)
            {
                NN_dic[num] = true;
                return true;
            }
            NN_dic[num] = false;
            return false;
        }
예제 #27
0
        public void can_compute_1000_results_using_generator()
        {
            //Arrange fib(999)
            BigInteger fib999 = new BigInteger(2)
                                * new BigInteger(17)
                                * new BigInteger(53)
                                * new BigInteger(73)
                                * new BigInteger(109)
                                * new BigInteger(149)
                                * new BigInteger(1997)
                                * new BigInteger(2221)
                                * new BigInteger(12653)
                                * new BigInteger(16061684237)
                                * new BigInteger(124134848933957)
                                * new BigInteger(1459000305513721)
                                * BigInteger.Parse("930507731557590226767593761")
                                * BigInteger.Parse("1687733481506255251903139456476245146806742007876216630876557")
                                * BigInteger.Parse("49044806374722940739127188459343134898237532255227554514970877");

            //Act
            var results = FibPro("--g 1000");
            var sequence = results.StandardOut.Split(' ');

            //Assert
            Assert.AreEqual(fib999.ToString("R0"), sequence.Last());
            Assert.AreEqual(SUCCESS, results.ExitCode);
        }
        public static bool verifyPrime(BigInteger p)
        {
            string strP = p.ToString();

            Dictionary<char, int> decNumbers = new Dictionary<char, int>
            {
               {'0', 0},{'1', 1},{'2', 2},{'3', 3}, {'4', 4},
               {'5', 5},{'6', 6},{'7', 7}, {'8', 8},{'9', 9},
            };

            //перевыряєм чи число p ділиться на 2
            if (dividedBy2(strP, decNumbers) == false)
                return false;

            //перевыряєм чи число p ділиться на 3
            if (dividedBy3(strP, decNumbers) == false)
                return false;

            //перевыряєм чи число p ділиться на 5
            if (dividedBy5(strP, decNumbers) == false)
                return false;

            //перевыряєм чи число p ділиться на 7
            if (dividedBy7(strP, decNumbers) == false)
                return false;

            //перевыряєм чи число p ділиться на 11
            if (dividedBy11(strP, decNumbers) == false)
                return false;

            return true;
        }
 public static BigInteger getNextPalindrome(BigInteger num)
 {
     int len = num.ToString().Length;
     if (len == 1)
     {
         if (num == new BigInteger(9)) return new BigInteger(11);
         return num + 1;
     }
     else
     {
         int firstHalfPow = (len % 2 == 0) ? len / 2 : len / 2 + 1;
         int secondHalfPow = len / 2;
         BigInteger first = num / ((int) Math.Pow(10, firstHalfPow));
         BigInteger second = num % ((int) Math.Pow(10, secondHalfPow));
         BigInteger firstInverse = BigInteger.Parse(string.Join("", first.ToString().Reverse()));
         if (firstInverse > second)
         {
             return num + (firstInverse - second);
         }
         else if (second > firstInverse)
         {
             BigInteger compl = new BigInteger((int)Math.Pow(10, secondHalfPow));
             return getNextPalindrome(num + (compl - second));
         }
         else
         {
             return getNextPalindrome(num + 1);
         }
     }
 }
 static void Main(String[] args)
 {
     int n = Convert.ToInt32(Console.ReadLine());
     BigInteger factorial = new BigInteger(1);
     factorial = f(n);
     Console.WriteLine(factorial.ToString());
 }
예제 #31
0
        static void Main(string[] args)
        {
            //start the clock
            Stopwatch clock = Stopwatch.StartNew();

            //Main function goes here
            Console.Write("Input your number: ");
            BigInteger numberInput = new BigInteger();
            numberInput = BigInteger.Parse(Console.ReadLine());
            BigInteger total = new BigInteger();
            total = Factorial(numberInput);
            string finalNum = total.ToString();
            int sum = 0;
            for (int i = 0; i < finalNum.Length; i++ )
            {
                sum += int.Parse(finalNum[i].ToString());
            }

            //Stop the clock
            clock.Stop();

            //print the result
            Console.WriteLine("The sum of the digits in the number {0}! is: {1}", numberInput, sum);
            Console.WriteLine("The solution took {0}ms to complete.", clock.ElapsedMilliseconds);
            Console.ReadKey();
        }
예제 #32
0
 public string GetFactorial(int n)
 {
     System.Numerics.BigInteger result = 1;
     for (int i = n; i > 0; i--)
     {
         result *= i;
     }
     return(result.ToString("#,##0"));
 }
예제 #33
0
 // Token: 0x06000D43 RID: 3395 RVA: 0x00053C54 File Offset: 0x00051E54
 public override void WriteValue(object value)
 {
     if (value is System.Numerics.BigInteger)
     {
         System.Numerics.BigInteger bigInteger = (System.Numerics.BigInteger)value;
         base.InternalWriteValue(JsonToken.Integer);
         this.WriteValueInternal(bigInteger.ToString(CultureInfo.InvariantCulture), JsonToken.String);
         return;
     }
     base.WriteValue(value);
 }
예제 #34
0
        protected internal string base36ToBase10(string s)
        {
            // This function will convert a number that has been generated
            // with functin above, and get the actual number in decimal
            //
            // This function requieres Mega Math to work correctly.

            string allowedLetters = licenseCharacters;

            System.Numerics.BigInteger result = new System.Numerics.BigInteger();
            for (int i = 0; i <= s.Length - 1; i += 1)
            {
                BigInteger pow = powof(allowedLetters.Length, (s.Length - i - 1));
                result = result + allowedLetters.IndexOf(s.Substring(i, 1)) * pow;
            }

            return(result.ToString()); //not sure
        }
    /// <summary>
    /// Generates a minecraft-style hash of a string
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string SHAHash(byte[] input)
    {
        using (var sha = SHA1.Create())
        {
            byte[] digest = sha.ComputeHash(input);
            var    bigint = new System.Numerics.BigInteger(digest.Reverse());

            // if the digest is "negative", flip it using BigInteger. otherwise, supply original digest
            if (bigint.Sign == -1)
            {
                bigint = -bigint;
                return("-" + bigint.ToString("x"));
            }
            else
            {
                return(BitConverter.ToString(digest.Reverse()).Replace("-", "").ToLower().TrimStart('0'));
            }
        }
    }
예제 #36
0
        private string base26ToBase10(string stringValue)
        {
            // This function will convert a number that has been generated
            // with functin above, and get the actual number in decimal
            //
            // This function requieres Mega Math to work correctly.

            var allowedLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var result         = new System.Numerics.BigInteger();


            for (var i = 0; i <= stringValue.Length - 1; i += 1)
            {
                var pow = powof(26, (stringValue.Length - i - 1));

                result = result + allowedLetters.IndexOf(stringValue.Substring(i, 1)) * pow;
            }

            return(result.ToString());
        }
        /// <summary>Processes the input using the slow method.</summary>
        /// <param name="textList">The text list.</param>
        /// <param name="counter">The counter.</param>
        /// <param name="caseStats">The case stats.</param>
        /// <returns></returns>
        public static List <string> ProcessSlow(string[] textList, int counter, List <string> caseStats)
        {
            Stopwatch stopWatch = new Stopwatch();

            // Splits the numbers into a string array and converts it into an integer array
            string[] caseList     = textList[counter].Split(' ');
            int[]    caseIntegers = Array.ConvertAll(caseList, s => int.Parse(s));

            System.Numerics.BigInteger permutations = 1;


            // SLOW METHOD...
            // finds all permutations of the list of numbers using 'Permutations'
            // calculates the sum of the Ray Shot Lengths for each permutation using 'RayShotsLength'
            // divides this number by permutations to give the score for the list
            stopWatch.Start();
            int score = 0;

            permutations = 0;
            IList <IList <int> > perms = Permutations(caseIntegers);

            foreach (List <int> perm in perms)
            {
                score        = score + RayShotsLength(perm);
                permutations = permutations + 1;
            }

            decimal slowAnswer = (decimal)score / (decimal)permutations;

            caseStats.Add(textList[counter] + " ... Average Score: " + slowAnswer.ToString("0.00")
                          + ", Permutations: " + permutations.ToString("#,###"));

            counter += 2;
            if (counter <= Convert.ToInt32(textList[0]) * 2)
            {
                ProcessSlow(textList, counter, caseStats);
            }

            // Returns detailed string output to client.html as txtResult
            return(caseStats);
        }
예제 #38
0
        //static System.Numerics.BigInteger p = ECCMain.HexToBigInteger.inputHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3");
        //static System.Numerics.BigInteger a = ECCMain.HexToBigInteger.inputHex("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA");
        //static System.Numerics.BigInteger b = ECCMain.HexToBigInteger.inputHex("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723");
        //static System.Numerics.BigInteger x = ECCMain.HexToBigInteger.inputHex("81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822");
        //static System.Numerics.BigInteger y = ECCMain.HexToBigInteger.inputHex("7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892");
        //static System.Numerics.BigInteger q = ECCMain.HexToBigInteger.inputHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069");

        private static void Test()
        {
            //var p = ECCMain.HexToBigInteger.inputHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3");
            Random rm         = new Random(DateTime.Now.GetHashCode());
            int    hash       = rm.Next(0, int.MaxValue);
            var    privateKey = (new System.Numerics.BigInteger(rm.Next(0, int.MaxValue))) * (new System.Numerics.BigInteger(rm.Next(0, int.MaxValue))) * (new System.Numerics.BigInteger(rm.Next(0, int.MaxValue))) * (new System.Numerics.BigInteger(rm.Next(0, int.MaxValue)));

            privateKey = privateKey % p;

            //var A = ECCMain.HexToBigInteger.inputHex("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA");
            //var B = ECCMain.HexToBigInteger.inputHex("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723");

            BigInteger[] doubleP = new System.Numerics.BigInteger[] { x, y };
            int          k       = 1;
            bool         isZero  = false;

            while (!isZero)
            {
                //Console.WriteLine($"{k},{k % 19}×G={doubleP[0]},{doubleP[1]}");
                doubleP = getDoubleP(doubleP, out isZero);
                k       = k * 2;
                if (k >= 1900000)
                {
                    break;
                }
            }


            BigInteger[] result = null;
            BigInteger[] baseP  = new System.Numerics.BigInteger[] { x, y };
            Console.WriteLine("输入整数");
            var        xx = Console.ReadLine();
            BigInteger startIndex;

            if (xx == "q")
            {
                Console.WriteLine($"{q.ToString()}");
                startIndex = q;
            }
            else
            {
                startIndex = BigInteger.Parse(xx);;
            }
            var r = get(startIndex);

            //bool isZero = false;
            for (int i = 0; i < r.Length; i++)
            {
                if (!r[i])
                {
                    if (baseP == null)
                    {
                    }
                    else
                    {
                        if (result == null)
                        {
                            result = baseP;
                        }
                        else
                        {
                            result = pointPlus(result, baseP, out isZero);

                            //Console.WriteLine($"baseP{i} ={baseP[0]},{baseP[1]}");
                        }
                        //  result = result == null ? baseP : pointPlus(result, baseP);
                    }
                }
                baseP = getDoubleP(baseP, out isZero);
            }



            if (result == null)
            {
                Console.WriteLine($"结果为空元");
            }
            else
            {
                Console.WriteLine($"{startIndex},{startIndex % q}×G={result[0]},{result[1]}");
            }

            //result = pointPlus(new BigInteger[] { 10, 6 }, new BigInteger[] { 7, 6 }, out isZero);
            //Console.WriteLine($"result  ={result[0]},{result[1]}");
            //result = pointPlus(result, new BigInteger[] { 10, 11 }, out isZero);
            //Console.WriteLine($"result  ={result[0]},{result[1]}");
            //result = pointPlus(result, new BigInteger[] { 13, 7 }, out isZero);
            //Console.WriteLine($"result  ={result[0]},{result[1]}");
            //BigInteger[] itemP = new System.Numerics.BigInteger[] { x, y };
            //BigInteger[] baseP = new System.Numerics.BigInteger[] { x, y };
            //int kk = 1;
            //bool isZero = false;
            //do
            //{
            //    Console.WriteLine($"{kk}×1={itemP[0]},{itemP[1]}");

            //    itemP = pointPlus(itemP, baseP, out isZero);
            //    kk++;
            //}
            //while (!isZero);
            //int k = 0;
            //while (!(doubleP[0] - a).IsZero)
            //{
            //    doubleP = getDoubleP(doubleP);
            //    k++;
            //    if (k % 1000 == 0)
            //        Console.WriteLine($"{k}");
            //}
            // var privateKey
            //  int hash=Random
            //   throw new NotImplementedException();
            //Console.WriteLine($"按Enter键继续");
            //Console.ReadLine();
        }
예제 #39
0
 public static void SetBigInt(string key, BigInt value)
 {
     PlayerPrefs.SetString(key, value.ToString());
 }
예제 #40
0
        public System.Numerics.BigInteger[] Merge(Part[][] parts, int threshold)
        {
            Org.BouncyCastle.Math.BigInteger p1 = new Org.BouncyCastle.Math.BigInteger(p.ToString());
            Console.WriteLine("p1" + p1.ToString());
            int secretSize = parts[0].Length;

            Console.WriteLine("secretsize" + secretSize);
            System.Numerics.BigInteger[] results = new System.Numerics.BigInteger[secretSize];
            string[] secret = new string[secretSize];
            byte[]   ba;
            string   str;
            int      count = 0;

            // loop through each secret partition
            for (int i = 0; i < secretSize; i++)
            {
                Sum = System.Numerics.BigInteger.Zero;
                //doing lagrange interpolation
                for (int j = 0; j < threshold; j++)
                {
                    mult = System.Numerics.BigInteger.One;
                    for (int k = 0; k < threshold; k++)
                    {
                        if (j != k)
                        {
                            System.Numerics.BigInteger numerator   = parts[k][i].GetX();
                            System.Numerics.BigInteger denominator = System.Numerics.BigInteger.Subtract(numerator, parts[j][i].GetX());

                            // take mod of negative number
                            while (System.Numerics.BigInteger.Compare(denominator, System.Numerics.BigInteger.Zero) < 0)
                            {
                                denominator = System.Numerics.BigInteger.Add(denominator, p);
                            }
                            //convert to bouncycastle biginteger to calculate modInverse
                            Org.BouncyCastle.Math.BigInteger denominator1 = new Org.BouncyCastle.Math.BigInteger(denominator.ToString());

                            Org.BouncyCastle.Math.BigInteger invDenominator1 = denominator1.ModInverse(p1);

                            System.Numerics.BigInteger invDenominator = System.Numerics.BigInteger.Parse(invDenominator1.ToString());

                            mult = System.Numerics.BigInteger.Multiply(mult, System.Numerics.BigInteger.Multiply(numerator, invDenominator));

                            mult = System.Numerics.BigInteger.Remainder(mult, p);
                        }
                    }
                    mult = System.Numerics.BigInteger.Multiply(mult, parts[j][i].GetY());

                    mult = System.Numerics.BigInteger.Remainder(mult, p);

                    Sum = System.Numerics.BigInteger.Add(Sum, mult);

                    Sum = System.Numerics.BigInteger.Remainder(Sum, p);
                }

                results[i] = Sum;
            }
            foreach (System.Numerics.BigInteger r in results)
            {
                //Console.WriteLine(r);
                //System.Numerics.BigInteger.TryParse
                ba  = r.ToByteArray();
                str = Encoding.UTF8.GetString(ba);
                //Console.WriteLine(str);
                secret[count++] = str;
            }
            str = string.Join("", secret);
            str.Replace("\n", "");
            return(results);
        }
예제 #41
0
        static private string invokeContract_NEP5_transfer(string NEP5hash, string addrTo, System.Numerics.BigInteger amount)
        {
            JArray inputJA = JArray.Parse(@"
                  [
                    '(str)transfer',
                        [
                            '(addr)[1]',
                            '(addr)[2]',
                            '(int)[3]'
                        ]
                  ]
                ".Replace("[1]", neoAddress.addrStr).Replace("[2]", addrTo).Replace("[3]", amount.ToString()));

            return(nTX.sendSimpleInvokeTx(neoAddress, neoAddress.addrStr, NEP5hash, inputJA));
        }
예제 #42
0
 // 获取某个块的难度
 static public double GetDiff(string hash)
 {
     System.Numerics.BigInteger bigint = System.Numerics.BigInteger.Parse("0" + hash, System.Globalization.NumberStyles.HexNumber);
     bigint = (diff_max - bigint) * 10000000000000000 / diff_max;
     return(double.Parse(bigint.ToString()) / 10000000000000000);
 }
예제 #43
0
    internal void ThreadPoolCallback(Object threadContext)
    {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();
        int threadIndex = (int)threadContext;

        _output += $"Thread {threadIndex} started...{Environment.NewLine}";
        FibOfN   = Calculate(N);
        _output += $"Thread {threadIndex} for Fibonacii(n = {N}) calculated in {stopwatch.Elapsed} with {FibOfN.ToString().Length} digits...{Environment.NewLine}";
        _doneEvent.Set();
    }
예제 #44
0
 // Token: 0x06000B53 RID: 2899 RVA: 0x0000E9C3 File Offset: 0x0000CBC3
 private static string ToStringInternal(System.Numerics.BigInteger value)
 {
     return(value.ToString(null, CultureInfo.InvariantCulture));
 }
예제 #45
0
        async void OnViewTranClicked(object sender, EventArgs e)
        {
            try
            {
                stqrcodeview.IsVisible = false;

                if (sendtran.IsVisible)
                {
                    sendtran.IsVisible    = false;
                    tranloading.IsVisible = sendtran.IsVisible;
                    return;
                }
                Button but     = (sender as Button);
                var    address = but.CommandParameter;
                if (address != null)
                {
                    addfrom.Text = address.ToString();

                    sendtran.IsVisible    = true;
                    tranloading.IsVisible = sendtran.IsVisible;
                    System.Numerics.BigInteger e_gas = 0;
                    Uri                 uri          = new Uri(App.ethapiurl);
                    HttpClient          client       = new HttpClient();
                    string              json         = "";
                    StringContent       content      = new StringContent("");
                    HttpResponseMessage response     = null;
                    addpwd.Text     = "";
                    addto.Text      = "";
                    tranamount.Text = "";
                    traegas.Text    = "";
                    tranprice.Text  = "";
                    tranprice.Text  = Nethereum.Web3.Web3.Convert.ToWei(50, UnitConversion.EthUnit.Gwei).ToString();
                    if (selcionflag.ToLower() == "eth")
                    {
                        json     = "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"" + address.ToString() + "\",\"to\":\"" + address.ToString() + "\"}]}";
                        content  = new StringContent(json, Encoding.UTF8, "application/json");
                        response = client.PostAsync(uri, content).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string        result       = response.Content.ReadAsStringAsync().Result;
                            var           resultJson   = JsonConvert.DeserializeObject <dynamic>(result);
                            string        money_hex    = resultJson.result;
                            HexBigInteger money_bigint = new HexBigInteger(money_hex);
                            e_gas = money_bigint.Value + 10000;
                        }
                    }
                    else
                    {
                        string queryaddress = address.ToString();
                        string data         = EthHelper.CallContractFunData("balanceOf(address)", new List <object> {
                            queryaddress
                        });

                        json     = "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"" + queryaddress + "\",\"to\":\"" + contractAddress + "\",\"data\":\"" + data + "\"}]}";
                        content  = new StringContent(json, Encoding.UTF8, "application/json");
                        response = client.PostAsync(uri, content).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string        result       = response.Content.ReadAsStringAsync().Result;
                            var           resultJson   = JsonConvert.DeserializeObject <dynamic>(result);
                            string        money_hex    = resultJson.result;
                            HexBigInteger money_bigint = new HexBigInteger(money_hex);
                            e_gas = money_bigint.Value + 50000;
                        }
                    }

                    if (e_gas > 0)
                    {
                        traegas.Text = e_gas.ToString();
                        json         = "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"eth_gasPrice\",\"params\":[]}";
                        content      = new StringContent(json, Encoding.UTF8, "application/json");
                        response     = client.PostAsync(uri, content).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string        result       = response.Content.ReadAsStringAsync().Result;
                            var           resultJson   = JsonConvert.DeserializeObject <dynamic>(result);
                            string        money_hex    = resultJson.result;
                            HexBigInteger money_bigint = new HexBigInteger(money_hex);

                            decimal eprice = Math.Round(Nethereum.Util.UnitConversion.Convert.FromWei(money_bigint.Value * e_gas), 8);
                            egas.Text      = "fee:" + eprice;// + (decimal.Parse((e_gas + 10000).ToString()) * eprice);
                            tranprice.Text = money_bigint.Value.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Exception!", "Try again later " + ex.Message, "OK");
            }
        }
예제 #46
0
        /// <summary>
        /// Execute the expression.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void executeExpression_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                uint   variableSize = 0U;
                double result       = 0.0;
                Dictionary <string, double> variables = new Dictionary <string, double>();

                // Execute the expression.
                string expression        = expressionWindowText.Text;
                string expressionReplace = expression;
                string expressionResult  = "";

                // Create the math object.
                Nequeo.Math.MathGenerics <bool> math = new Nequeo.Math.MathGenerics <bool>();

                string[] names  = null;
                string[] values = null;

                // Get the variables.
                if (!String.IsNullOrEmpty(variableNamesText.Text) &&
                    !String.IsNullOrEmpty(variableValuesText.Text))
                {
                    names  = variableNamesText.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    values = variableValuesText.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    // For each variable.
                    for (int i = 0; i < names.Length; i++)
                    {
                        try
                        {
                            // Add variables.
                            variables.Add(names[i].Trim(), Double.Parse(values[i].Trim()));

                            // Replace variable with value.
                            //expressionReplace = expressionReplace.Replace(names[i].Trim(), "(" + values[i].Trim() + ")");
                        }
                        catch { }
                    }

                    // If multi variable.
                    if (variables.Count > 1)
                    {
                        variableSize = 2U;
                    }
                    else
                    {
                        variableSize = 1U;
                    }
                }

                // Select the extra operation index.
                switch (customExceuteOp.SelectedIndex)
                {
                case 10:
                    // Exponential Integral Function
                    string[] exponential = expression.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    double   xExp        = Double.Parse(exponential[0].ToString().Trim());
                    int      nExp        = Int32.Parse(exponential[1].ToString().Trim());

                    result            = Nequeo.Science.Math.SpecialFunctions.ExponentialIntegral(xExp, nExp);
                    expressionResult  = result.ToString();
                    expressionReplace = "Exponential Integral Function : \r\n" +
                                        "x = " + xExp.ToString() + ", n = " + nExp.ToString();
                    break;

                case 9:
                    // Regularized Lower Incomplete Beta Function.
                    // I_x(a,b) = 1/ Beta(a,b) * int(t^(a-1)*(1-t)^(b-1),t=0..x) for real a > 0, b > 0, 1 >= x >= 0.
                    string[] beta  = expression.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    double   aBeta = Double.Parse(beta[0].ToString().Trim());
                    double   bBeta = Double.Parse(beta[1].ToString().Trim());
                    double   xBeta = Double.Parse(beta[2].ToString().Trim());

                    result            = Nequeo.Science.Math.SpecialFunctions.BetaRegularized(aBeta, bBeta, xBeta);
                    expressionResult  = result.ToString();
                    expressionReplace = "Regularized Lower Incomplete Beta Function : \r\n" +
                                        "I_x(a,b) = 1/ Beta(a,b) * int(t^(a-1)*(1-t)^(b-1),t=0..x) for real a > 0, b > 0, 1 >= x >= 0\r\n" +
                                        "a = " + aBeta.ToString() + ", b = " + bBeta.ToString() + ", x = " + xBeta.ToString();
                    break;

                case 8:
                    // Binomial n choose k
                    string[] binomial = expression.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    int      nB       = Int32.Parse(binomial[0].ToString().Trim());
                    int      kB       = Int32.Parse(binomial[1].ToString().Trim());

                    result            = Nequeo.Science.Math.SpecialFunctions.Binomial(nB, kB);
                    expressionResult  = result.ToString();
                    expressionReplace = "Binomial n choose k : \r\n" + nB.ToString() + " choose " + kB.ToString();
                    break;

                case 7:
                    // Factorial n!
                    System.Numerics.BigInteger nF     = new System.Numerics.BigInteger(Double.Parse(expression.Trim()));
                    System.Numerics.BigInteger bitInt = Nequeo.Science.Math.SpecialFunctions.Factorial(nF);
                    expressionResult  = bitInt.ToString();
                    expressionReplace = "Factorial n! : \r\n" + nF.ToString() + "!";
                    break;

                case 6:
                    // Cubic Roots a*x^3 + b*x^2 + c*x + d = 0.
                    Tuple <Complex, Complex, Complex> cubicRoots = Nequeo.Science.Math.FindRoots.Cubic(variables["b"], variables["c"], variables["b"], variables["a"]);
                    expressionResult  = "Real = " + cubicRoots.Item1.Real.ToString() + ", Imaginary = " + cubicRoots.Item1.Imaginary.ToString() + "\r\n";
                    expressionResult += "Real = " + cubicRoots.Item2.Real.ToString() + ", Imaginary = " + cubicRoots.Item2.Imaginary.ToString() + "\r\n";
                    expressionResult += "Real = " + cubicRoots.Item3.Real.ToString() + ", Imaginary = " + cubicRoots.Item3.Imaginary.ToString();
                    expressionReplace = "Cubic Roots a*x^3 + b*x^2 + c*x + d = 0 : \r\n" + expressionReplace;
                    break;

                case 5:
                    // Quadratic Roots a*x^2 + b*x + c = 0.
                    Tuple <Complex, Complex> quadraticRoots = Nequeo.Science.Math.FindRoots.Quadratic(variables["c"], variables["b"], variables["a"]);
                    expressionResult  = "Real = " + quadraticRoots.Item1.Real.ToString() + ", Imaginary = " + quadraticRoots.Item1.Imaginary.ToString() + "\r\n";
                    expressionResult += "Real = " + quadraticRoots.Item2.Real.ToString() + ", Imaginary = " + quadraticRoots.Item2.Imaginary.ToString();
                    expressionReplace = "Quadratic Roots a*x^2 + b*x + c = 0 : \r\n" + expressionReplace;
                    break;

                case 4:
                    // Equation Root f(x) = 0.
                    object[] expressionParameters = (variables.Count > 0 ? new object[variables.Count] : null);
                    int      varIndex             = 0;

                    // Replace the expression.
                    string hidedExpression = ReplaceExpressionHide(expression.Trim());

                    // For each variable.
                    foreach (KeyValuePair <string, double> item in variables)
                    {
                        // Replace the variable names.
                        hidedExpression = hidedExpression.Replace(item.Key, "@" + varIndex++.ToString());

                        // Add the variable parameter.
                        expressionParameters[varIndex - 1] = item.Value;
                    }

                    // Replace the expression.
                    string replacedExpression = ReplaceExpression(hidedExpression.Trim());

                    // A parameter for the lambda expression.
                    System.Linq.Expressions.ParameterExpression paramExpr = System.Linq.Expressions.Expression.Parameter(typeof(double), "x");
                    ParameterExpression[] pe = new List <ParameterExpression>()
                    {
                        paramExpr
                    }.ToArray();
                    LambdaExpression lambda = Nequeo.Linq.DynamicExpression.ParseLambda(pe, typeof(double), replacedExpression.Trim(), expressionParameters);

                    // Get the function.
                    Func <double, double> function = (Func <double, double>)lambda.Compile();
                    result = Nequeo.Science.Math.FindRoots.OfFunction(function, Double.Parse(aVariableEquationRoot.Text), Double.Parse(bVariableEquationRoot.Text));

                    expressionReplace = "Equation Root f(x) = 0 : \r\n" + expressionReplace + " = 0";
                    expressionResult  = result.ToString();
                    break;

                case 3:
                    // Linear Algebra.
                    // Use managed provider to solver system.
                    ILinearAlgebraProvider <double> provider = new ManagedLinearAlgebraProvider();

                    // Variable names.
                    names = variableNamesText.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    // Get row and column lengths.
                    string[] aRowColumn = aColumnsRowsLinearAlgebra.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    int      aRow       = Int32.Parse(aRowColumn[0].Trim());
                    int      aColumn    = Int32.Parse(aRowColumn[1].Trim());
                    int      bColumn    = Int32.Parse(bColumnsLinearAlgebra.Text.Trim());

                    // Variables.
                    double[] a = new double[aRow * aColumn];
                    double[] b = new double[aRow * bColumn];

                    // Get the equation.
                    string[] equations = expression.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int eq = 0; eq < equations.Length; eq++)
                    {
                        // Current equation.
                        string[] eqAB = equations[eq].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                        // Assign B vector.
                        b[eq] = Double.Parse(eqAB[1].Trim());

                        // Get each variable.
                        string[] eqA = eqAB[0].Replace("-", "+ -").Replace("+ - ", "+ -").Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int equa = 0; equa < eqA.Length; equa++)
                        {
                            // Get current value.
                            string currentRowColumnValue = eqA[equa];

                            // Replace variable names.
                            for (int v = 0; v < names.Length; v++)
                            {
                                // Remove variable name.
                                currentRowColumnValue = currentRowColumnValue.Replace(names[v].Trim(), "");
                            }

                            // Convert to double.
                            double aRCValue = Double.Parse(
                                (String.IsNullOrEmpty(currentRowColumnValue.Trim()) ? "1" :
                                 (currentRowColumnValue.Trim() == "-" ? "-1" : currentRowColumnValue.Trim()))
                                );

                            // Assign the A matrix.
                            a[(eq * aRow) + equa] = aRCValue;
                        }
                    }

                    // Re-arrage A.
                    double[] ax = new double[aRow * aColumn];
                    for (int row = 0; row < aRow; row++)
                    {
                        for (int column = 0; column < aColumn; column++)
                        {
                            // Assign
                            ax[(row * aRow) + column] = a[row + (column * aColumn)];
                        }
                    }

                    // The result.
                    double[] x = new double[names.Length];

                    // Solver the system.
                    provider.SvdSolve(ax, aRow, aColumn, b, bColumn, x);

                    // The result.
                    for (int z = 0; z < x.Length; z++)
                    {
                        // Result string.
                        expressionResult += names[z].Trim() + " = " + x[z].ToString() + "\r\n";
                    }
                    expressionReplace = "System Linear Equation Solver : \r\n" + expressionReplace;
                    break;

                case 2:
                    // Derivative.
                    result            = math.ExpressionDerivative <double>(expression, Double.Parse(xVariableDerivative.Text), "x", variables);
                    expressionReplace = "Derivative at (" + xVariableDerivative.Text + ") : " + expressionReplace;
                    expressionResult  = result.ToString();
                    break;

                case 1:
                    // Integrate.
                    result            = math.ExpressionIntegrate <double>(expression, 0.0, "x", Double.Parse(aVariableIntegrate.Text), Double.Parse(bVariableIntegrate.Text), variables);
                    expressionReplace = "Integral at (x) interval [" + aVariableIntegrate.Text + ", " + bVariableIntegrate.Text + "] : " + expressionReplace;
                    expressionResult  = result.ToString();
                    break;

                case 0:
                default:
                    // Select the variable number.
                    switch (variableSize)
                    {
                    case 2U:
                        result           = math.ExpressionMulti <double>(expression, variables);
                        expressionResult = result.ToString();
                        break;

                    case 1U:
                        result           = math.Expression <double>(expression, variables.Values.First(), variables.Keys.First());
                        expressionResult = result.ToString();
                        break;

                    case 0U:
                    default:
                        result           = math.Expression <double>(expression);
                        expressionResult = result.ToString();
                        break;
                    }
                    break;
                }

                // Display the result.
                UI.ResultWindow resultWindow = new UI.ResultWindow(expressionResult, expressionReplace);
                resultWindow.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Scientific Calculator", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #47
0
 public override string ToString()
 {
     return(string.Format("{0}:{1}:{2}:{3}:{4}",
                          iInt64.ToString(), iDouble.ToString(), iComplex.ToString(), iBigInt.ToString(), iString));
 }