A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime, as only 1 and 5 divide it.

For computing prime numbers we will use Sieve of Eratosthenes algorithm. The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so).

# Algorithm

To find all the prime numbers less than or equal to a given integer *n* by Eratosthenes’ method:

- Create a list of consecutive integers from 2 to
*n*: (2, 3, 4, …,*n*). - Initially, let
*p*equal 2, the first prime number. - Starting from
*p*, count up in increments of*p*and mark each of these numbers greater than*p*itself in the list. These numbers will be 2*p*, 3*p*, 4*p*, etc.; note that some of them may have already been marked. - Find the first number greater than
*p*in the list that is not marked. If there was no such number, stop. Otherwise, let*p*now equal this number (which is the next prime), and repeat from step 3.

When the algorithm terminates, all the numbers in the list that are not marked are prime

public static void PrimeNumber(int n) { int[] numbers = new int[n + 1]; if (n < 0) { Console.WriteLine("invalid value"); return; } if (n < 3) { Console.WriteLine("Prime number is : 2"); return; } int p = 0; for (int i = 2; i <= n; i++) { if (numbers[i] == 0) { p = i; for (int j = 2; p * j <= n; j++) { numbers[p * j] = 1; } } } for (int i = 2; i <= n; i++) { if (numbers[i] == 0) Console.Write(i + " , "); } }

Filed under:
Number

Leave a comment