Some numbers are considered special because of their unique properties. One type of special number is called a Prime number.We will first understand what is a prime number and then write a small program in C# that can check if a number is prime or not.
What is a Prime Number?
A prime number is a special number that can only be divided evenly by 1 and itself. That means if you try to divide it by any other number, you’ll receive a remainder. Examples of such prime numbers are 2, 3, 5, 7, and 11. Try dividing them with other numbers, excluding 1 and themselves; they won’t divide even. That’s what makes it prime!
Prime numbers are useful in many areas, such as in cryptography to keep your data safe across the internet. Learning how to check for a prime number is one of those first steps toward understanding programming and algorithms.
Simple Program in C# to Check for Prime Numbers
Let’s assume we have a number, and we want to see whether it is a prime or not. We can make this prime number verification program in C#. We will go through it step by step.
using System;
class PrimeChecker
{
static void Main()
{
Console.WriteLine("Enter a number:");
int number = int.Parse(Console.ReadLine());
if (IsPrime(number))
Console.WriteLine(number + " is a prime number.");
else
Console.WriteLine(number + " is not a prime number.");
}
static bool IsPrime(int number)
{
if (number <= 1) return false;
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0)
return false;
}
return true;
}
}
Breaking Down the Code: What Each Part Means
Main() Method
The first point at which the program will start running is here. Inside the main, we are asking the user to input a number and then calling a method named IsPrime to check whether the number is prime or not.
IsPrime Method
The method IsPrime consists of the actual logic, that takes a number and checks if it’s prime or not.
if (number <= 1)
This checks if the number is less than or equal to 1. Since we are interested in numbers greater than 1 only , we immediately return false in this case.
for (int i = 2; i <= Math.Sqrt(number); i++)
Here, we loop from 2 up to the square root of the number. According to the prime number algorithm we loop till the square root.
if (number % i == 0)
This line checks whether the number is divisible by i. If it is then it means the number has a divisor other than 1 and itself-it’s not a prime.
Returning value of either True or False
If we find a divisor then we return false-not prime. When the loop finishes without finding any of the divisors then we return true, which means that the number is prime.
In this simple program, we looked at the logic of checking if a number is prime or not, step by step. Every time you run this program with a different number, it will verify if the number is prime or not.
Follow on: