コード例 #1
0
ファイル: AddingBigNumbers.cs プロジェクト: Sanyam07/impls
        public static string Add(string a, string b)
        {
            var lhs = PositiveBigInteger.Parse(a);
            var rhs = PositiveBigInteger.Parse(b);
            var sum = PositiveBigInteger.Add(lhs, rhs);

            return(sum.ToString());
        }
コード例 #2
0
ファイル: AddingBigNumbers.cs プロジェクト: Sanyam07/impls
        public static PositiveBigInteger Add(PositiveBigInteger lhs, PositiveBigInteger rhs)
        {
            var  minLength  = Math.Min(lhs._bits.Length, rhs._bits.Length);
            var  maxLength  = Math.Max(lhs._bits.Length, rhs._bits.Length);
            var  sumBits    = new uint[maxLength];
            var  longerBits = maxLength == lhs._bits.Length ? lhs._bits : rhs._bits;
            uint carry      = 0;

            for (var i = 0; i < minLength; i++)
            {
                var currentSum = lhs._bits[i] + rhs._bits[i] + carry;
                if (currentSum >= MaxUnits)
                {
                    sumBits[i] = currentSum - MaxUnits;
                    carry      = 1;
                }
                else
                {
                    sumBits[i] = currentSum;
                    carry      = 0;
                }
            }

            for (var i = minLength; i < maxLength; i++)
            {
                var currentSum = longerBits[i] + carry;
                if (currentSum >= MaxUnits)
                {
                    sumBits[i] = currentSum - MaxUnits;
                    carry      = 1;
                }
                else
                {
                    sumBits[i] = currentSum;
                    carry      = 0;
                }
            }

            if (carry == 1)
            {
                var oldSumBits = sumBits;
                sumBits = new uint[oldSumBits.Length + 1];
                for (var i = 0; i < oldSumBits.Length; i++)
                {
                    sumBits[i] = oldSumBits[i];
                }

                sumBits[sumBits.Length - 1] = 1;
            }

            return(new PositiveBigInteger(sumBits));
        }