Código Java – Números Primos

// Codificado por: Beastieux
// Listar los números primos según el número de dígitos indicado

public class SyGNumerosPrimos {
    public static void main(String arg[]) {
        if (arg.length < 1) {
            System.out.println("Debe ingresar un número de dígitos como parámetro.");
            return;
        }

        int numDigitos = Integer.parseInt(arg[0]);
        
        if (numDigitos <= 0) {
            System.out.println("Ingrese un número de dígitos válido (mayor que 0).");
            return;
        }

        for (int i = (int) Math.pow(10, numDigitos - 1); i < Math.pow(10, numDigitos); i++) {
            if (esPrimo(i)) {
                System.out.println(i);
            }
        }
    }

    public static boolean esPrimo(int num) {
        if (num <= 1) {
            return false;
        }

        if (num <= 3) {
            return true;
        }

        if (num % 2 == 0 || num % 3 == 0) {
            return false;
        }

        int i = 5;

        while (i * i <= num) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }

            i += 6;
        }

        return true;
    }
}

Pueder ir al artículo principal:

Códigos Sencillos hechos en Java

4 thoughts on “Código Java – Números Primos

  1. hola, primo(1) y primo(0) dan true? una forma mas rapida de saber si es primo… de forma sencilla se me ocurre:

    public static boolean primo(int n){
    //verifico que no sea par o que sea 1
    n = Math.abs(n);
    if(n&1)==0 && n!=2) || n==1)return false;
    for(int i=3;i<(int)(Math.sqrt(n))+1;i+=2){
    if(n%i==0)return false;
    }
    return true;
    }

    de la misma forma contarDigitos podria ser

    public static int contarDigitos(int numeroEntero){
    return String.valueOf(numeroEntero).length();
    }

Deja un comentario