24 Feb 2024




Beginner

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and itself, and it cannot be formed by multiplying two smaller natural numbers.

For example, some of the prime numbers include:

  • 2 (the smallest prime number) , 3, 5, 7, 9, 11, 13, 17 .....
using System;

class PrimeChecker
{
    public static bool IsPrime(int number)
    {
        if (number <= 1)
        {
            return false; // 1 and numbers less than 1 are not prime
        }

        // Check for divisibility from 2 to the square root of the number
        for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
        {
            if (number % divisor == 0)
            {
                return false; // If number is divisible by any divisor, it's not prime
            }
        }

        return true; // If no divisors are found, the number is prime
    }

    static void Main(string[] args)
    {
        Console.Write("Enter a number to check if it's prime: ");
        int number = Convert.ToInt32(Console.ReadLine());

        if (IsPrime(number))
        {
            Console.WriteLine(number + " is a prime number.");
        }
        else
        {
            Console.WriteLine(number + " is not a prime number.");
        }
    }
}

Explanation:

  • The IsPrime method takes an integer number as input and returns a boolean indicating whether the number is prime or not.

  • We start by checking if the number is less than or equal to 1. If it is, we return false since 1 and numbers less than 1 are not considered prime.

  • We iterate through all potential divisors from 2 up to the square root of the number. We only need to check up to the square root because if a number is divisible by a factor greater than its square root, the other factor would be less than the square root, and we would have already checked it.

  • For each divisor, we check if the number is divisible by it using the modulo operator (%). If the remainder is 0, then the number is divisible by the divisor, meaning it's not a prime number.

  • If the loop completes without finding any divisors, the number is determined to be prime and we return true.

  • In the Main method, we prompt the user to enter a number, call the IsPrime method to check if it's prime, and then output the result to the console.