Factorial Sencillo 2 en JAVA usando recursión y BigInteger

8 03 2009

Hola, por recomendación de mi viejo amigo phi mejore el código utilizando recursión y el tipo de dato BigInteger para no limitar al usuario a ingresar máximo un N de 20.

package javacertificationdmk.capitulo2;
import java.math.BigInteger;
import java.io.*;

/***
 *

Nombre      : FactorialSencillo.java

 *

Descripción : Se obtiene el factorial por recursividad usando BigInteger

 *

Fecha       : Marzo 7 de 2009

 * @author        : [D-m-K]
 * @version       : 1.0.0
 ***/

public class FactorialSencillo2 {
  public static void main(String[] args) throws IOException{
        //Pido el número
        System.out.println("\n\t O B T E N E R   F A C T O R I A L \n");
        int n = leerN("\t Ingresa el valor de N para obtener factorial : ");
        BigInteger factorial = obtenerFactorial(n);

        //Obtengo el factorial del número ingresado
        System.out.println("\n\t [R E S U L T A D O]\n");
        System.out.println("\t El factorial de " + n + " es : " + factorial);

  }

  /**
   * @param msg - Mensaje a mostrar para solicitar el valor de entrada
   * @return n - Valor ingresado de tipo entero
   * @throws java.io.IOException
   */
  public static int leerN (String msg) throws IOException{
      int n = 0;
      boolean error;
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      do{
        error = false;
        try{
            System.out.print(msg);
            n = Integer.parseInt(br.readLine());
            if(n < 1){
                System.out.println("\t ERROR : El numero no puede ser negativo\n");
                error = true;
            }
        }catch(NumberFormatException e){
            System.out.println("\t ERROR : El valor ingresado no es numerico\n");
            error = true;
        }
      }while(error);

      return n;
  }

  /**
   * @param n - numero a calcular
   * @return fac - Factorial del numero a calcular de tipo BigInteger
   */
  public static BigInteger obtenerFactorial(int n){
      if(n <= 1){
          return (new BigInteger("1"));
      }else{
          BigInteger fac = new BigInteger(String.valueOf(n));
          return (fac.multiply(obtenerFactorial(n - 1)));
      }
  }

}

PTA: Por fín estoy usando bien la documentación xDDD

Greetings to all and happy BandWidth.


Acciones

Información

Deja un comentario