Skip to content
Create a gist now

Instantly share code, notes, and snippets.

anonymous /Primer.cs
Created May 16, 2013

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
Something went wrong with that request. Please try again.