Thursday, November 30, 2017

Simple function to check if the number is prime (c# / .NET)


The function is for the beginners as a sample function to check if the input number is a prime number. It takes a number as argument and returns a boolean result. I have used a very basic algorithm to check if the number is prime. Also, negative numbers are neglected.

public bool IsPrime(int number)
        {
            if (number < 2)
                return false;
            else if (number <= 3)
                return true;

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

Further, you can use the following facts and optimize above function to find if the number is prime.
  • The number divisible by itself and by 1 is a prime number.
  • 2 is only the even prime number. 
  • if the sum of individual digits of the number is divisible by 3, then the number is divisible by 3
  • We do not consider 0 and 1 as a prime number.
  • Except 5, no numbers ending with 5 is prime.


No comments:

Post a Comment