Exemplo n.º 1
0
        /// <summary>
        /// Calculates a product of a two ALong instances, a.k.a "School" method (very slow)
        /// </summary>
        /// <param name="num1">Multiplicand</param>
        /// <param name="num2">Multiplier</param>
        /// <returns>Product of num1 and num2.</returns>

        //TODO: replace with Karatsuba, Schönhage–Strassen or Knuth. (Fast Fourier transform?).
        //TODO: use base of size of Int32 to "shorten" sizes of numbers within multiplication speed being kept.
        public static ALong Mul(ALong num1, ALong num2)
        {
            var result = new ALong(0);

            if (num1 == 0 || num2 == 0)
            {
                return(result);
            }
            var carry = 0;

            for (int i = 0; i < num1.Length(); i++)
            {
                var n1    = num1.GetRNumAtIndex(i);
                var res   = String.Empty;
                var n2len = num2.Length();
                carry = 0;
                for (int k = 0; k < n2len; k++)
                {
                    var n2 = num2.GetRNumAtIndex(k);
                    var ns = n1 * n2 + carry;
                    carry = ns / 10;
                    res   = (ns % 10) + res;
                    if (k == n2len - 1 && carry > 0)
                    {
                        res = carry.ToString() + res;
                    }
                }
                var mulres = new ALong(res);
                mulres.MulBase(i);
                result += mulres;
            }
            if (num1.IsNegative != num2.IsNegative)
            {
                result.SetNegative(true);
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Calculates a Summary of a two ALong absolute values, a.k.a "School" method.
        /// </summary>
        /// <param name="num1">First addend</param>
        /// <param name="num2">Second addend</param>
        /// <returns>ALong instance representing a sum of two addends.</returns>
        private static ALong AbsSum(ALong num1, ALong num2)
        {
            var result = String.Empty;
            int carry  = 0;
            var max    = Math.Max(num1.Length(), num2.Length());

            for (int i = 0; i < max; i++)
            {
                var n1 = num1.GetRNumAtIndex(i);
                var n2 = num2.GetRNumAtIndex(i);
                var ns = n1 + n2 + carry;
                carry = 0;
                if (ns >= 10)
                {
                    ns = ns - 10; carry = 1;
                }
                result = ns.ToString() + result;
                if (i == max - 1 && carry > 0)
                {
                    result = carry.ToString() + result;
                }
            }
            return(new ALong(result));
        }