Exemplo n.º 1
0
        public static async Task <BigInteger> Gcd(BigInteger a, BigInteger b)  // GCD - Greatest common divisor
        {
            var tcs = new TaskCompletionSource <BigInteger>();

            new Thread(Calculation).Start();

            return(await tcs.Task);

            async void Calculation()
            {
                try
                {
                    // Get a collection of prime numbers by decomposing the numbers a, b
                    var dataA = await ThreadLib.FactorizationAsync(a);

                    var dataB = await ThreadLib.FactorizationAsync(b);

                    // Get a collection of tuples (prime number, least count of repetitions) from two prime sets
                    var fin = from a1 in dataA.GroupBy(ab => ab).Select(g => new { Num = g.Key, Count = g.Count() })
                              from b1 in dataB.GroupBy(ab => ab).Select(g => new { Num = g.Key, Count = g.Count() })
                              where a1.Num == b1.Num
                              select a1.Count > b1.Count ? b1 : a1;

                    BigInteger gcd = 1;

                    // Multiply all primers from the fin query
                    foreach (var element in fin)
                    {
                        gcd *= BigInteger.Pow(element.Num, element.Count);
                    }

                    tcs.SetResult(gcd);
                }

                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }
        }
Exemplo n.º 2
0
        private static void Main(string[] args)
        {
            var sw = Stopwatch.StartNew();

            foreach (var element in Lib.Factorization(2005000000000050000))
            {
                Console.WriteLine(element);
            }
            sw.Stop();

            Console.WriteLine($"Factorization = {sw.ElapsedMilliseconds} ms");


            sw.Restart();
            var task = ThreadLib.FactorizationAsync(2005000000000050000);

            foreach (var element in task.Result)
            {
                Console.WriteLine(element);
            }
            sw.Stop();

            Console.WriteLine($"FactorizationAsync = {sw.ElapsedMilliseconds} ms");

            try
            {
                var bigInteger1 = new BigInteger(192634096486);
                bigInteger1 *= 2120778898307;
                var bigInteger2 = new BigInteger(2120778898307);

                Console.WriteLine($"Processing GSD of {bigInteger1} and  {bigInteger2}");
                Console.WriteLine($"GSD = {AsyncLibGcd.Gcd(bigInteger1, bigInteger2).Result}");
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }