ellapt

T7.15.PrimeNumbers

Jan 15th, 2013
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class primeNumbers
  6. {
  7. static void Main()
  8. {
  9. Console.WriteLine("Find all prime numbers in the range [1...10 000 000]");
  10. int n = 10000000;
  11. var iterNum = 1;
  12. // Enumerable class provides methods for querying objects that implement IEnumerable<T>
  13. List<int> arr = Enumerable.Range(2, n-1).ToList();
  14.  
  15. double k=Math.Sqrt(n); // The upper limit to check
  16. while (iterNum <= k)
  17. {
  18. int work = iterNum;
  19. int work2 = arr.First(i => i > work); // return the first element i > work
  20. arr.RemoveAll(i => i != work2 && i % work2 == 0); // remove all elements (i != work2 && i % work2 == 0)
  21. iterNum = work2; // next iteration
  22. }
  23.  
  24. // Print the result
  25. int[] arrOut = arr.ToArray();
  26. for (int i = 0; i < arrOut.Length; i++)
  27. {
  28. Console.WriteLine(arrOut[i]);
  29. }
  30. }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment