fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. var pgm = new Test();
  10. pgm.DoStuff();
  11. Console.WriteLine("Done. Press Enter.");
  12. Console.ReadLine();
  13. }
  14.  
  15. private void DoStuff()
  16. {
  17. const int MaxPrime =
  18. 1000000;
  19. // 22307;
  20. for (var i = 0; i < 2; ++i)
  21. {
  22. var sw = Stopwatch.StartNew();
  23. var primes = FindPrimes(MaxPrime);
  24. sw.Stop();
  25. var ms = (1000.0*sw.ElapsedTicks)/Stopwatch.Frequency;
  26. Console.WriteLine("{0:N0} primes found in {1} ms ({2})", primes.Count, ms, sw.ElapsedMilliseconds);
  27. }
  28. Console.WriteLine();
  29. }
  30.  
  31. private List<int> FindPrimes(int maxVal)
  32. {
  33. var primes = new List<int>{2};
  34. for (var x = 3; x <= maxVal; x += 2 )
  35. {
  36. var maxDiv = (int) Math.Round(Math.Sqrt(x));
  37. bool isPrime = true;
  38. for (var i = 1; i < primes.Count && primes[i] <= maxDiv; ++i)
  39. {
  40. if ((x%primes[i]) == 0)
  41. {
  42. isPrime = false;
  43. break;
  44. }
  45. }
  46. if (isPrime)
  47. {
  48. primes.Add(x);
  49. }
  50. }
  51. return primes;
  52. }
  53. }
Success #stdin #stdout 1.02s 37184KB
stdin
Standard input is empty
stdout
78,498 primes found in 471.6898 ms (471)
78,498 primes found in 514.6837 ms (514)

Done. Press Enter.