find the nth prime number in csharp

To find the nth prime number, we will first write a function to check if a number is prime or not. Then, we will use a loop to iterate through numbers until we find the nth prime.

Here's the code:

main.cs
public bool IsPrime(int number)
{
    if (number < 2)
        return false;

    for (int i = 2; i <= Math.Sqrt(number); i++)
    {
        if (number % i == 0)
            return false;
    }

    return true;
}

public int FindNthPrime(int n)
{
    int count = 0;
    int number = 2;

    while (count < n)
    {
        if (IsPrime(number))
            count++;

        number++;
    }

    return number - 1;
}
416 chars
30 lines

In the IsPrime function, we first check if the number is less than 2 (since 1 is not considered a prime number). Then, we iterate through all the numbers from 2 to the square root of the number. If the number is divisible by any of these numbers, it is not a prime number and we return false. Otherwise, we return true.

In the FindNthPrime function, we initialize a count variable to 0 and a number variable to 2 (the first prime number). We loop through all the numbers, checking if each number is prime. If it is, we increment the count variable. When the count variable reaches n, we return the current number minus 1 (since we have already incremented it once before exiting the loop).

gistlibby LogSnag