Search

Calculate prime numbers

This C# code snippet uses a BitArray to calculate the prime numbers over then range 2-n.
using System;
using System.Collections;
 
const int LAST_CANDIDATE = 1000;
int primes = 0;
BitArray candidates = new BitArray (LAST_CANDIDATE, true);
 
for (int i = 2; i < LAST_CANDIDATE; i++)
{
   if (candidates[i])
   {
      for (int j = i * 2; j < LAST_CANDIDATE; j += i)
         { candidates[j] = false; }
   }
}
 
for (int i = 1; i < LAST_CANDIDATE; i++)
{
   if (candidates[i])
   {
      primes++;
      Console.Out.WriteLine (i);
   }
}
 
Console.Out.WriteLine
   ("\n" + primes + " primes found in the range 2-" + LAST_CANDIDATE);