Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class Cribe {
- static int maxN = (int) 1e7;
- static boolean cribe[] = new boolean[maxN];
- static Scanner scanner = new Scanner(System.in);
- static void initCribe()
- {
- Arrays.fill(cribe, true);
- cribe[0] = (cribe[1] = false);
- for(int i = 2; i*i < maxN; i++)
- {
- if(cribe[i])
- {
- for(int j = i*i; j < maxN; j+=i)
- {
- cribe[j] = false;
- }
- }
- }
- }
- static int forceReadPositiveInt(String message)
- {
- int n = 0;
- while(true)
- {
- try
- {
- System.out.println(message);
- n = Integer.parseInt(scanner.next());
- if(n > -1 ) return n;
- System.out.println("El número a testear debe ser mayor o igual a 0:.");
- continue;
- }
- catch(Exception ex)
- {
- System.out.println("Se introdujo un número inválido, reintente.");
- }
- }
- }
- public static void main(String[] args) {
- initCribe();
- while(true)
- {
- int x = forceReadPositiveInt("Ingrese número a testear:");
- System.out.println(cribe[x] ? "Es primo" : "No es primo");
- System.out.println("¿Continuará con los tests? (S/N)");
- if(scanner.next().charAt(0) == 'N') break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment