C# Method to Check if a Number is Prime

If you participate in competitive programming assessment, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter.

In this post, we will write a C# method to check if a number is a prime but first let's explain what is a prime number. 

What is a Prime Number

A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole number 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. A natural number greater than 1 that is not prime is called a composite number. The integer 1 is neither prime nor composite number.

A prime number can be used for a variety of purposes. For instance, some types of cryptography rely on prime numbers.

Going by definition, a Prime number is a positive integer that is divisible only by itself and 1. The Greek mathematician Euclid, demonstrated in ancient times that there are infinitely many primes.

To calculate whether a number is prime or not, we have used a for/loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0. Here is the complete C# code to check if an integer number is a prime or not.

public static bool IsPrime(int n)
{
    if (n < 2) return false;
    if (n % 2 == 0) return (n == 2);
    int root = (int)Math.Sqrt((double)n);
    for (int i = 3; i <= root; i += 2)
    {
        if (n % i == 0) return false;
    }
    return true;
}

Do you have better solution? Please share it with us in the comments. Thank you!

Post a Comment

Previous Post Next Post