Skip to content

Instantly share code, notes, and snippets.

@thinktainer
Created May 24, 2013 17:52
Show Gist options
  • Save thinktainer/5645283 to your computer and use it in GitHub Desktop.
Save thinktainer/5645283 to your computer and use it in GitHub Desktop.
from msdn
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
int maxPrime = 100;
List<int> primes = GetPrimes(maxPrime);
Console.WriteLine("Primes less than {0}:", maxPrime);
Console.WriteLine(" {0}", String.Join(" ", primes));
}
private static List<int> GetPrimes(int maxPrime)
{
Array values = Array.CreateInstance(typeof(int),
new int[] { maxPrime - 1}, new int[] { 2 });
// Use Sieve of Erathsthenes to determine prime numbers.
for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
{
if ((int) values.GetValue(ctr) == 1) continue;
for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
if (ctr * multiplier <= maxPrime)
values.SetValue(1, ctr * multiplier);
}
List<int> primes = new List<int>();
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
if ((int) values.GetValue(ctr) == 0)
primes.Add(ctr);
return primes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment