Created
July 2, 2013 18:44
-
-
Save riyadparvez/5911941 to your computer and use it in GitHub Desktop.
Finds all the prime numbers up to n using Sieve of Eratosthenes in C#. See http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static IList<int> SieveOfEratosthenes(int n) | |
| { | |
| if(n < 2) | |
| { | |
| throw new ArgumentOutOfRangeException(); | |
| } | |
| var arr = Enumerable.Repeat(true, n+1).ToArray(); | |
| for (int i = 2; i <= n; i++) | |
| { | |
| if(arr[i]) | |
| { | |
| int j = 2; | |
| int mul = 0; | |
| while((mul = (j*i)) <= n) | |
| { | |
| arr[mul] = false; | |
| j++; | |
| } | |
| } | |
| } | |
| var primes = new List<int>(); | |
| for (int i=2; i <= n; i++) | |
| { | |
| if(arr[i]) | |
| { | |
| primes.Add(i); | |
| } | |
| } | |
| return primes; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment