C# program to check if a number is prime or not
Here's a C# program to check if a number is prime or not:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
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.");
}
}
static bool IsPrime(int number)
{
if (number <= 1)
{
return false;
}
if (number == 2)
{
return true;
}
if (number % 2 == 0)
{
return false;
}
for (int i = 3; i <= Math.Sqrt(number); i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
In this program, the IsPrime method takes an integer number as input and checks if it is a prime number. It first checks for some special cases: if the number is less than or equal to 1, it returns false; if the number is 2, it returns true. Then, it checks if the number is divisible by 2. If it is, it returns false. After that, it iterates from 3 up to the square root of the number and checks if the number is divisible by any odd number in that range. If it is, it returns false. If none of the conditions are met, the number is considered prime and it returns true.
The Main method prompts the user to enter a number, calls the IsPrime method with the user input, and displays the appropriate message based on the result.
Note that the program assumes the user will input a positive integer. It doesn't handle exceptions if the input is not a valid positive integer.