Exemplo n.º 1
0
        /// <summary>
        /// Adds n1 and n2 and puts result in dest, without intermediate memory allocation
        /// (unsafe if n1 and n2 disagree in precision, safe even if dest is n1 or n2)
        /// </summary>
        /// <param name="dest"></param>
        /// <param name="n1"></param>
        /// <param name="n2"></param>
        public static void SubFast(BigInt dest, BigInt n1, BigInt n2)
        {
            //We cast to the highest input precision...
            if (n1.digitArray.Length != n2.digitArray.Length) MakeSafe(ref n1, ref n2);

            //Then we up the output precision if less than the input precision.
            if (dest.digitArray.Length < n1.digitArray.Length) n1.MakeSafe(ref dest);

            int Length = n1.digitArray.Length;

            if (n1.sign != n2.sign)
            {
                //Copies sources into digit array and working set for all cases, to avoid
                //problems when dest is n1 or n2
                for (int i = 0; i < Length; i++)
                {
                    dest.workingSet[i] = n2.digitArray[i];
                    dest.digitArray[i] = n1.digitArray[i];
                }
                dest.AddInternalBits(dest.workingSet);
                dest.sign = n1.sign;
            }
            else
            {
                bool lessThan = LtInt(n1, n2);

                if (lessThan)
                {
                    for (int i = 0; i < Length; i++)
                    {
                        dest.workingSet[i] = n1.digitArray[i];
                        dest.digitArray[i] = n2.digitArray[i];
                    }
                    dest.SubInternalBits(dest.workingSet);
                    dest.sign = !n1.sign;
                }
                else
                {
                    for (int i = 0; i < Length; i++)
                    {
                        dest.workingSet[i] = n2.digitArray[i];
                        dest.digitArray[i] = n1.digitArray[i];
                    }
                    dest.SubInternalBits(dest.workingSet);
                    dest.sign = n1.sign;
                }
            }
        }