Foros aprenderaprogramar.com
Aprender a programar => C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más => Mensaje iniciado por: Dimitar Stefanov en 18 de Julio 2016, 20:49
-
Ejercicio:
Write a program that reads an integer N (which will always be less than 100 or equal) and uses an expression to check if given N is prime (i.e. it is divisible without remainder only to itself and 1).
Note: You should check if the number is positive
El código:
using System;
class Program {
static void Main() {
int num = -1;
while(num < 0 || num > 100) {
Console.Write("Introducir un número entero de 0 a 100: ");
num = Convert.ToInt16(Console.ReadLine());
}
int result = 0;
for(int i = 2;i<=Math.Sqrt(num);i++) {
if(num%i == 0) {
result = result+1;
}
}
if(num==0 || num==1) {
Console.WriteLine("False");
}else if(num==2) {
Console.WriteLine("True");
}else {
if(result>0) {
Console.WriteLine("False");
}else {
Console.WriteLine("True");
}
}
}
}
Saludos.