Exercise
Prime number
Objetive
Write a C# program that asks the user for an integer and determines if it is a prime number or not.
Example Code
using System; // Import the System namespace, which contains fundamental classes like Console
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user to enter an integer
Console.Write("Enter an integer: ");
int number = int.Parse(Console.ReadLine()); // Read and convert the user input to an integer
// Check if the number is less than 2, as prime numbers are greater than 1
if (number < 2)
{
Console.WriteLine("The number is not prime."); // If the number is less than 2, it's not prime
}
else
{
bool isPrime = true; // Assume the number is prime unless proven otherwise
// Check divisibility from 2 to the square root of the number
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0) // If the number is divisible by i, it's not prime
{
isPrime = false; // Set isPrime to false if a divisor is found
break; // Exit the loop as we've found a divisor
}
}
// Display whether the number is prime or not
if (isPrime)
{
Console.WriteLine("The number is prime."); // If no divisors were found, it's prime
}
else
{
Console.WriteLine("The number is not prime."); // If a divisor was found, it's not prime
}
}
}
}