Created
May 16, 2013 15:21
-
-
Save anonymous/5592511 to your computer and use it in GitHub Desktop.
Calculates prime numbers
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 Primer | |
{ | |
public int[] GetPrimes(int max) | |
{ | |
if (max < 0) max = max * -1; | |
if (max < 2) | |
throw new ArgumentException("argument should be at least 2"); | |
bool[] primeIndexes = new bool[max + 1]; // +1 because we're not using index 0, but we actually do need the last number (say, if max is 10, we actually need index 10 in array, so length is 11) | |
int start = 2; | |
while ((start = GetNextStartNum(primeIndexes, start)) > 0) | |
{ | |
for (int i = start * start; i < primeIndexes.Length; i += start) | |
{ | |
primeIndexes[i] = true; | |
} | |
start++; | |
} | |
List<int> primes = new List<int>(max / 10); | |
for (int i = 1; i < primeIndexes.Length; i++) | |
{ | |
if (primeIndexes[i] == false) | |
primes.Add(i); | |
} | |
return primes.ToArray(); | |
} | |
private static int GetNextStartNum(bool[] primeIndexes, int minIndex) | |
{ | |
if (minIndex * minIndex > primeIndexes.Length) | |
return 0; | |
for (int i = minIndex; i < primeIndexes.Length; i++) | |
{ | |
if (primeIndexes[i] == false) | |
return i; | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment