Boost Your Programming Skills: C# Program for Prime Number Verification
using System;
namespace PrimeNumberChecker
{
class Program
{
static void Main(string[] args)
{
Console.Write("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.");
}
}
public static bool IsPrime(int number)
{
if (number <= 1)
return false; // Not prime if less than or equal to 1
if (number == 2)
return true; // 2 is prime
// Start checking from 2
for (int i = 2; i * i <= number; i++)
{
if (number % i == 0)
return false; // Not prime if divisible by any i
}
return true; // Return true if it is prime
}
}
}
This program defines a function `IsPrime` that checks whether the input number is prime. It handles special cases (less than or equal to 1 and 2) and then iterates from 2 up to the square root of the number to determine primality. If the number is divisible by any integer in this range, it is not prime; otherwise, it is considered prime¹⁴. Feel free to try it out! .
using System;
namespace PrimeNumberChecker
{
class Program
{
static void Main(string[] args)
{
Console.Write("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.");
}
}
public static bool IsPrime(int number)
{
if (number <= 1)
return false; // Not prime if less than or equal to 1
if (number == 2)
return true; // 2 is prime
// Start checking from 2
for (int i = 2; i * i <= number; i++)
{
if (number % i == 0)
return false; // Not prime if divisible by any i
}
return true; // Return true if it is prime
}
}
}
This program defines a function `IsPrime` that checks whether the input number is prime. It handles special cases (less than or equal to 1 and 2) and then iterates from 2 up to the square root of the number to determine primality. If the number is divisible by any integer in this range, it is not prime; otherwise, it is considered prime¹⁴. Feel free to try it out! .