Skip to content

Instantly share code, notes, and snippets.

Created May 16, 2013 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5592511 to your computer and use it in GitHub Desktop.
Save anonymous/5592511 to your computer and use it in GitHub Desktop.
Calculates prime numbers
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