public void Multiply(Natural factor1, Natural factor2)
        {
            if (factor1 == Natural.Zero || factor2 == Natural.Zero)
            {
                factor1.SetValue(Natural.Zero);
            }
            else if (factor1 == Natural.One)
            {
                factor1.SetValue(factor2);
            }
            else
            {
                Natural increase = factor1.Clone();
                Natural decrease = factor2.Clone();

                factor1.PushLength(factor1.usedDigits * factor2.usedDigits);

                while (decrease > 1) // We already have 1 factor1
                {
                    Natural.Add(factor1, increase);
                    Natural.Decrement(decrease);
                }

                factor1.PopLength();
            }
        }
        public void Multiply(Natural factor1, Natural factor2, out Natural product)
        {
            if (factor1 == Natural.Zero || factor2 == Natural.Zero)
            {
                product = Natural.Zero;
            }
            else if (factor1 == Natural.One)
            {
                product = factor2.Clone();
            }
            else
            {
                Natural counter = factor2.Clone();
                product = factor1.Clone();

                product.PushLength(factor1.usedDigits * factor2.usedDigits);

                while (counter > 1) // We already have 1 factor1
                {
                    Natural.Add(product, factor1);
                    Natural.Decrement(counter);
                }

                product.PopLength();
            }
        }
Ejemplo n.º 3
0
        public void Add(Natural x, Natural y)
        {
            int length = Math.Max(x.usedDigits, y.usedDigits);

            x.PushLength(length + 1);
            y.PushLength(length); // Expand so we know we can index those digits

            Digit carry = 0;
            for (int i = 0; i < length; i++)
            {
                Carry res = (Carry)x.digits[i] + y.digits[i] + carry;
                Digit val;
                if (res > Digit.MaxValue)
                {
                    carry = 1;
                    val = (Digit)(res - Digit.MaxValue - 1);
                }
                else
                {
                    carry = 0;
                    val = (Digit)res;
                }

                x.digits[i] = val;
            }
            x.digits[length] = carry;
            x.usedDigits = length + (int)carry; // If carry == 1 we used another extra digit

            x.PopLength();
            y.PopLength();
        }