Esempio n. 1
0
        public static BigInt Substract(BigInt number1, BigInt number2)
        {
            bool ResIsNegative = number1.IsNegative;

            if (number1.isNegative && !number2.IsNegative)//-+
            {
                return(Sum(number1, new BigInt(number2.number, !number2.IsNegative)));
            }

            if (!number1.isNegative && number2.IsNegative)//+-
            {
                return(Sum(number1, new BigInt(number2.number, !number2.IsNegative)));
            }

            int length = number1.number.Length;

            if (number1.number.Length < number2.number.Length)
            {
                length = number2.number.Length;
            }

            StringBuilder sbNum1 = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                try
                {
                    sbNum1.Append(number1.number[number1.number.Length - i - 1]);
                }
                catch
                {
                    sbNum1.Append("0");
                }
            }

            StringBuilder sbNum2 = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                try
                {
                    sbNum2.Append(number2.number[number2.number.Length - i - 1]);
                }
                catch
                {
                    sbNum2.Append("0");
                }
            }

            if (!FirstBigger(number1, number2))
            {
                StringBuilder sbSwap = sbNum1;
                sbNum1 = sbNum2;
                sbNum2 = sbSwap;
                //ako 2roto e po golqmo, se obrushta znaka!!!
                ResIsNegative = !ResIsNegative;
            }

            string ResNumber;
            int    curr1;
            int    curr2;
            int    curr;
            int    NaUm = 0;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                try
                {
                    curr1 = int.Parse(sbNum1[i].ToString());
                }
                catch
                {
                    curr1 = 0;
                }
                try
                {
                    curr2 = int.Parse(sbNum2[i].ToString());
                }
                catch
                {
                    curr2 = 0;
                }

                curr = (curr1 - curr2 - NaUm);
                NaUm = 0;
                if (curr < 0)
                {
                    curr += 10;
                    NaUm  = 1;
                }
                sb.Append(curr.ToString());
            }
            StringBuilder sbReverse = new StringBuilder();

            for (int i = sb.Length - 1; i >= 0; i--)
            {
                sbReverse.Append(sb[i]);
            }
            ResNumber = sbReverse.ToString();

            return(new BigInt(ResNumber, ResIsNegative));
        }