Grupo
Conceptos básicos control de flujo en C#
Objectivo
Escriba un programa en C# que le pida al usuario un número entero y determine si es un número primo o no.
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
class Program
{
static void Main()
{
// Ask the user to input an integer
Console.Write("Enter an integer: ");
int number = int.Parse(Console.ReadLine()); // Read the number as an integer
// Check if the number is less than 2, as prime numbers are greater than 1
if (number <= 1)
{
Console.WriteLine($"{number} is not a prime number.");
}
else
{
bool isPrime = true; // Flag to indicate if the number is prime
// 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 number is divisible by i, it is not prime
{
isPrime = false;
break; // No need to check further, number is not prime
}
}
// Output whether the number is prime or not
if (isPrime)
{
Console.WriteLine($"{number} is a prime number.");
}
else
{
Console.WriteLine($"{number} is not a prime number.");
}
}
}
}
Output
//Example 1: Input = 7
Enter an integer: 7
7 is a prime number.
//Example 2: Input = 10
Enter an integer: 10
10 is not a prime number.
//Example 3: Input = 1
Enter an integer: 1
1 is not a prime number.
//Example 4: Input = 13
Enter an integer: 13
13 is a prime number.
Código de ejemplo copiado
Comparte este ejercicio de C#