import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String e = "";
do {
try {
System.out.println("Calcular si un número es primo: fin para salir");
e = br.readLine();
if (e.equalsIgnoreCase("fin")) {
System.out.println("Me despido.");
} else {
int n = Integer.parseInt(e);
if (n <= 1) {
System.out.println("El valor ha de ser mayor que 1");
} else {
long inicio = System.currentTimeMillis();
esPrimo(n);
long fin = System.currentTimeMillis();
System.out.println("Se ha tardado " + (fin - inicio) + " ms.");
}
}
} catch (IOException | NumberFormatException ex) {
System.out.println("Sólo valores numéricos, máximo 2147483647 por ser INT");
}
} while (!e.equalsIgnoreCase("fin"));
}
private static void esPrimo(int e) {
System.out.println("2");
for (int y = 2; y <= e; y++) {
if (y % 2 != 0) {
int x = y - 1;
do {
if (y % x == 0) {
x = 0;
} else {
x--;
if (x <= 1) {
x = 1;
}
}
} while (x > 1);
if (x == 1) {
System.out.println(y);
}
}
}
}
}
[/aux_code]
Benchmark
con
No hay comentarios
[aux_code language=»javascript» theme=»tomorrow» title=»Benchmark» extra_classes=»»]