Ejemplo n.º 1
0
        /// <summary>
        /// Computes the extended greatest common divisor, such that a*x + b*y = <c>gcd</c>(a,b).
        /// </summary>
        /// <param name="a">First Integer: a.</param>
        /// <param name="b">Second Integer: b.</param>
        /// <param name="x">Resulting x, such that a*x + b*y = <c>gcd</c>(a,b).</param>
        /// <param name="y">Resulting y, such that a*x + b*y = <c>gcd</c>(a,b)</param>
        /// <returns>Greatest common divisor <c>gcd</c>(a,b)</returns>
        /// <example>
        /// <code>
        /// long x,y,d;
        /// d = Fn.GreatestCommonDivisor(45,18,out x, out y);
        /// -> d == 9 &amp;&amp; x == 1 &amp;&amp; y == -2
        /// </code>
        /// The <c>gcd</c> of 45 and 18 is 9: 18 = 2*9, 45 = 5*9. 9 = 1*45 -2*18, therefore x=1 and y=-2.
        /// </example>
        public static BigInteger ExtendedGreatestCommonDivisor(BigInteger a, BigInteger b, out BigInteger x, out BigInteger y)
        {
            BigInteger mp = BigInteger.One, np = BigInteger.Zero, m = BigInteger.Zero, n = BigInteger.One;

            while (!b.IsZero)
            {
                BigInteger rem;
                BigInteger quot = BigInteger.DivRem(a, b, out rem);
                a = b;
                b = rem;

                BigInteger tmp = m;
                m  = mp - (quot * m);
                mp = tmp;

                tmp = n;
                n   = np - (quot * n);
                np  = tmp;
            }

            if (a >= BigInteger.Zero)
            {
                x = mp;
                y = np;
                return(a);
            }

            x = -mp;
            y = -np;
            return(-a);
        }
Ejemplo n.º 2
0
        public static BigInteger DivRem(BigInteger x, BigInteger y, out BigInteger remainder)
        {
            BigInt rem;
            BigInt result = BigInt.DivRem(x.Value, y.Value, out rem);

            remainder = new BigInteger(rem);
            return(new BigInteger(result));
        }