Tuesday, November 30, 2010

Generate HashSet of Prime numbers, check if Prime. Basic

public static HashSet<int> GetPrimes(int max)
{
  HashSet<int> primes = new HashSet<int>();
  for (int i = 2; i < max; i++)
   if (IsPrime(i))
    primes.Add(i);
  return primes;
}

private static bool IsPrime(int candidate)
{
  bool prime = true;
  double sqr = Math.Sqrt(candidate);
  for (int i = 2; i <= sqr; i++)
  {
   if (candidate % i == 0)
   {
    prime = false;
    break;
   }
  }
  return prime;
}

No comments:

Post a Comment