using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public class PrimeList
{
// A list of prime values.
private static readonly List<int> Primes = new List<int>( 10001 );
// An array of bits indicating whether the odd numbers (from 3 upwards)
// are prime (true) or non-prime (false).
private static readonly BitArray OddPrimeSieve = new BitArray( 100000,
true );
// The maximum prime number that has currently been found from the sieve.
private static int MaxSieved = 3;
static PrimeList()
{
Primes.Add( 2 );
Primes.Add( 3 );
}
public static int GetNthPrime( int index )
{
// Caclulate the sieve index of the currently maximum sieved prime.
int sieveIndex = ( MaxSieved - 3 ) / 2;
int multiple;
while( Primes.Count < index )
{
// Set all higher multiples of the current prime to be non-prime.
for ( multiple = sieveIndex + MaxSieved;
multiple < OddPrimeSieve.Count;
multiple += MaxSieved )
{
OddPrimeSieve.Set( multiple, false );
}
// Find the sieve index of the next prime number.
do
{
++sieveIndex;
}
while ( sieveIndex < OddPrimeSieve.Count
&& !OddPrimeSieve[sieveIndex] );
// Reverse the calculation of the sieve index to get the next prime.
MaxSieved = 2*sieveIndex + 3;
// Add the prime to the list.
Primes.Add( MaxSieved );
}
return Primes[index-1];
}
public static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
int p = GetNthPrime(10001);
sw.Stop();
Console.WriteLine( p );
Console.WriteLine( "Time to calculate in milliseconds : {0}",
sw.ElapsedMilliseconds );
}
}