In this example we’ll learn How to find Nth prime number in C#.

A **prime number** is a whole **number** greater than 1 whose only factors are 1 and itself. A factor is a whole **numbers** that can be divided evenly into another **number**. The first few **prime numbers** are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

**C# Code:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nth_prime { class Program { public static bool isPrime(int number) { int counter = 0; for (int j = 2; j < number; j++) { if (number % j == 0) { counter = 1; break; } } if (counter == 0) { return true; } else { return false; } } static void Main(string[] args) { int num=1; int count = 0; Console.Write("Number : " ); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); while (true) { num++; if(isPrime(num)) { count++; } if(count==n) { Console.WriteLine(n+"th prime number is "+num); break; } } Console.ReadKey(); } } } |