Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class PuntoCuatro {
- static Scanner scanner = new Scanner(System.in);
- static int forceReadPositiveInt()
- {
- int n = 0;
- while(true)
- {
- try
- {
- System.out.println("Introduzca el valor de N:");
- n = Integer.parseInt(scanner.next());
- if(n <= 0 )
- {
- System.out.println("El valor de N debe ser positivo.");
- continue;
- }
- return n;
- }
- catch(Exception ex)
- {
- System.out.println("Se introdujo un número inválido, reintente.");
- }
- }
- }
- static boolean isPrime(int n) // O(n^(1/2)) (SE PENSÓ UTILIZAR LA CRIBA DE ERATÓSTENES, PERO AL SER SOLO UN TEST DE UN PRIMO NO SE VERÍA REQUERIDA.
- {
- for(int i = 2; i*i <= n; i++)
- {
- if(n%i == 0)
- {
- return false;
- }
- }
- return true && n!= 1;
- }
- static void solve(int n)
- {
- System.out.println(isPrime(n) ? n+ " es un número primo." : n+ " no es un número primo.");
- }
- public static void main(String[] args) {
- int n = forceReadPositiveInt();
- solve(n);
- }
- }
Add Comment
Please, Sign In to add comment