Exemple #1
0
        public static bool Fermat(long n)
        {
            if (n <= 1 || n == 4)
            {
                return(false);
            }
            if (n <= 3)
            {
                return(true);
            }

            var random = new Random();

            for (int i = 0; i < FermatIterationCount; i++)
            {
                var m = random.Next(2, n - 2);

                if (GCD.EuclidNaive(n, m) != 1)
                {
                    return(false);
                }
                if (Exponentiation.Pow(m, n - 1, n) != 1)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #2
0
        /// <summary>
        /// Karatsuba is a fast multiplication algorithm
        /// </summary>
        public static long Karatsuba(long x, long y)
        {
            if (x < KaratsubaMinValue || y < KaratsubaMinValue)
            {
                return(x * y);
            }

            var n = Math.Max(GetSize(x), GetSize(y));
            var m = (n / 2) + (n % 2);
            var k = Exponentiation.BinExp(10, m);

            var a = (x / k);
            var b = (x % k);
            var c = (y / k);
            var d = (y % k);

            var z0 = Karatsuba(a, c);
            var z1 = Karatsuba(b, d);
            var z2 = Karatsuba(a + b, c + d);

            return((Exponentiation.BinExp(10, m * 2) * z0) + z1 + ((z2 - z1 - z0) * k));
        }