Read the previous post about prime numbers for knowing the rules and way to identify the number is prime number or not.
http://www.negablog.com/2015/04/how-to-check-number-is-prime-number-or.html
This post will tell you the way to find prime numbers between 1 to N (more than 1+ million) which takes maximum loading time of 500 ms only.

Lets find prime numbers between 1 to N.

"Sieve of Eratosthenes" which is simple and ancient algorithm for finding all prime numbers up to any given limit. Because checking each number for prime takes more loading time.
You can read about "Sieve of Eratosthenes" algorithm in Wikipedia,
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Also give you a quick overview about "Sieve of Eratosthenes" algorithm.
To find all the prime numbers less than or equal to 30, follow the steps.
- Identify the prime which multiples (or square) do not exceed 30. (5*5 = 25 < 30)
- Generate a list of integers from 2 to 30 (1 is not prime no)
- Eliminate the integers which are divisible by 2
- Now the list have numbers which are not divisible by 2. Next prime number is 3. Eliminate all the numbers which are divisible by 3.
- Next prime number is 5. Eliminate all the numbers which are divisible by 5.
- Next prime number is 7. Multiples of number 7 is 14, 21, 28 which are already eliminated. 7*7 is greater than 30. The
numbers which remains in the list are all the
prime numbers below 30.

**Code:**
double FindPrimeNumbers(int startIndex, int endIndex)

{

List<int> lstNumbers = new List<int>();

List<int> lstSievePrimeNumber = new List<int>();

PrimeNumber primeNumberIdentifier = new PrimeNumber();

int sieveMaxPrimeNo;

// It generates series of numbers in a list for
given range

lstNumbers.AddRange(Enumerable.Range(startIndex,
endIndex - 1));

// According to "Sieve of
Eratosthenes" algorithm, the multiples/square of

// number which should not exceed the endIndex

sieveMaxPrimeNo = Int32.Parse(Math.Round(Math.Sqrt(endIndex),
0).ToString());

// Identify the prime number of multiples

for (int i = sieveMaxPrimeNo; i >= startIndex; i--)

{

bool IsPrimeNumber =
primeNumberIdentifier.CheckIsPrimeNumber(i);

if (IsPrimeNumber == true)

{

sieveMaxPrimeNo = i;

break;

}

}

// Get all the prime numbers between start index
and multiples of end index

for (int i = startIndex; i <= sieveMaxPrimeNo; i++)

{

bool IsPrimeNumber =
primeNumberIdentifier.CheckIsPrimeNumber(i);

if (IsPrimeNumber == true)

{

lstSievePrimeNumber.Add(i);

}

}

// Eliminate the numbers which are divisble by
prime numbers

foreach (double sievePrimeNumber in lstSievePrimeNumber)

{

lstNumbers.RemoveAll(i => (i % sievePrimeNumber
== 0) &&

(i !=sievePrimeNumber));

}

}
List<int> lstPrimeNumbers = FindPrimeNumbers(2, 30);

// Output - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29