Example #1
0
        public void Int128RandomArithmetic()
        {
            Random rng = new Random(314159);

            foreach (Int128 x in GetRandomInt128(8, rng))
            {
                // Relation of addition to multiplication
                Assert.IsTrue(-x == -1 * x);
                Assert.IsTrue(0 == 0 * x);
                Assert.IsTrue(x == 1 * x);
                Assert.IsTrue(x + x == 2 * x);
                Assert.IsTrue(x + x + x == 3 * x);

                foreach (Int128 y in GetRandomInt128(8, rng))
                {
                    // Subtraction and addition are inverses
                    Assert.IsTrue(y + (x - y) == x);

                    // Division methods agree
                    Int128 q = Int128.DivRem(x, y, out Int128 r);
                    Assert.IsTrue(q == x / y);
                    Assert.IsTrue(r == x % y);

                    // Division and multiplication are inverses
                    Assert.IsTrue(q * y + r == x);
                }
            }
        }
Example #2
0
        public void Int128BigIntegerAgreement()
        {
            Random rng = new Random(3);

            foreach (Int128 u in GetRandomInt128(10, rng))
            {
                BigInteger u1 = BigInteger.Parse(u.ToString());
                foreach (Int128 v in GetRandomInt128(10, rng))
                {
                    BigInteger v1 = BigInteger.Parse(v.ToString());

                    // Comparison
                    Assert.IsTrue((u < v) == (u1 < v1));
                    Assert.IsTrue((u > v) == (u1 > v1));

                    // To discard possible higher order bits in BigInteger results,
                    // coerce the result into an Int128.

                    // Sum
                    Int128     s  = u + v;
                    BigInteger s1 = u1 + v1;
                    Assert.IsTrue((Int128)s1 == s);

                    // Difference
                    Int128     d  = u - v;
                    BigInteger d1 = u1 - v1;
                    Assert.IsTrue((Int128)d1 == d);

                    // Product
                    Int128     p  = u * v;
                    BigInteger p1 = u1 * v1;
                    Assert.IsTrue((Int128)p1 == p);

                    // Quotient
                    // Since results are guaranteed to fit in Int128, we can safely compare to BigInteger directly.
                    Int128     q  = Int128.DivRem(u, v, out Int128 r);
                    BigInteger q1 = BigInteger.DivRem(u1, v1, out BigInteger r1);
                    Assert.IsTrue((BigInteger)q == q1);
                    Assert.IsTrue((BigInteger)r == r1);
                }
            }
        }