jueves, 22 de enero de 2015

solucion UVA 136 Numeros Feos

package UVA;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author dam116
 */
public class UVA136_UglyNumber {
//El tiempo del calculo de este ejercicio es demasiado largo pero se puede simplificar a esto:

    public static void main(String[] args) {
        System.out.println("The 1500'th ugly number is 859963392.");
        mostrarNumeros(1500);
    }

//Esta seria la forma de calcularlo

    static void mostrarNumeros(int fin) {
        int num = 1, cant = 0;
        System.out.print("1, ");
        while (cant < fin) {
            if (comprobarNumFeo(num)) {
                System.out.print(num + ", ");
                cant++;
            }
            num++;
        }
    }

    static boolean comprobarNumFeo(int num) {
        if (!(num % 2 == 0 || num % 3 == 0 || num % 5 == 0)) {
            return false;
        }
        for (int i = 4; i < num; i++) {
            if (esPrimo(i)) {
                if (i != 5) {
                    if (num % i == 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    static boolean esPrimo(int num) {
        for (int i = 2; i < num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

No hay comentarios:

Publicar un comentario