Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Timers;
- namespace CSharpConcurrency
- {
- class Program
- {
- static StreamWriter individualCycles = new StreamWriter("./individual.txt");
- static StreamWriter overAll = new StreamWriter("./overall.txt");
- static StreamWriter finalCalcs = new StreamWriter("./finalCalcs.txt");
- static StreamWriter output = new StreamWriter("./output.txt");
- static void Main(string[] args)
- {
- #region TPL
- for (int i = 0; i < 10; i++)
- {
- Console.WriteLine(DateTime.Now);
- List<long> toCalculate = new List<long> {
- 13548153810,
- 24265915380,
- 35143815420,
- 41452967940,
- 52725472560,
- 63547825480,
- 74936756240, };
- Stopwatch clock = new Stopwatch();
- clock.Start();
- var results = toCalculate.AsParallel().Select(CalculatePrimes).ToList(); //Csharp TPL+LINQ magic -- Selects each long then runs CalculatePrimes on it, puts each returned result into a list matching the id of the longs list.
- clock.Stop();
- overAll.WriteLine(clock.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)));
- int minNum, maxNum;
- long smallest, largest;
- clock.Restart();
- minNum = results.Min(x => x.Count);
- maxNum = results.Max(x => x.Count);
- smallest = results.Min(x => x.Min());
- largest = results.Max(x => x.Max());
- clock.Stop();
- finalCalcs.WriteLine(clock.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)));
- clock.Restart();
- //Tested by comparing results
- Console.WriteLine("Smallest Number Of Prime Factors: " + minNum);
- Console.WriteLine("Largest Number Of Prime Factors: " + maxNum);
- Console.WriteLine("Smallest Prime Factor :" + smallest);
- Console.WriteLine("Largest Prime Factor :" + largest);
- clock.Stop();
- output.WriteLine(clock.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)));
- Console.WriteLine(DateTime.Now);
- individualCycles.Flush();
- overAll.Flush();
- finalCalcs.Flush();
- output.Flush();
- }
- Console.WriteLine("COMPLETELY FINISHED. PRESS ENTER TO EXIT");
- Console.ReadKey();
- }
- #endregion
- static List<long> CalculatePrimes(long number)
- {
- Stopwatch clock = new Stopwatch();
- clock.Start();
- List<long> primeNumbers = new List<long>();
- for (int i = 2; i < number; i++)
- {
- while (number % i == 0)
- {
- primeNumbers.Add(i);
- number /= i;
- }
- }
- clock.Stop();
- individualCycles.WriteLine(clock.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)));
- Console.WriteLine("Completed");
- return primeNumbers;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment