Created
November 20, 2012 05:49
-
-
Save markthiessen/4116270 to your computer and use it in GitHub Desktop.
Fetch Primes C#
This file contains 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 class PrimeFetcher | |
{ | |
public IEnumerable<int> FetchPrimesUpTo(int max) | |
{ | |
if (max <= 1) | |
return Enumerable.Empty<int>(); | |
var range = Enumerable.Range(0, max + 1).ToArray(); | |
range[1] = 0; | |
foreach (var number in range.Where(n => n != 0 && n <= max / 2)) | |
{ | |
foreach (var multiple in GetMultiples(number, max)) | |
range[multiple] = 0; | |
} | |
return range.Where(number => number != 0); | |
} | |
private static IEnumerable<int> GetMultiples(int number, int max) | |
{ | |
return Enumerable.Range(2, max / number).Select(multiplier => multiplier * number).Where(result => result <= max); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment