anonymous / Primer.cs
Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Calculates prime numbers

View Primer.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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.