Long Swap for BigInteger or BigDecimal?

0

I'm trying to read from the keyboard a very large integer, I saw that there are BigInteger or Bigdecimal types, I do not know if they are larger than Long.

I wanted to read from the keyboard numbers with 10 or 14 digits but Long is not supporting,

Could you be using one of these two types to do this? how?

 import java.util.Scanner; import java.math.BigDecimal;


 /**
  *
  * @author Mateus
  */
 public class Fatorial {

     /**
      * @param args the command line arguments
      */
     public static void main(String[] args) {
       long a=1,num,fat,res;
         String aa;
         Scanner ler = new Scanner (System.in);


         while (a == 1){
          res=1;   

                 System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------"); 
                 System.out.println("");

                     System.out.println("Digite o numero que vc queira descobrir seu fatorial:");   
         num = ler.nextLong();


         for (fat=1;fat<100000;fat++){
             res=fat*res;


             if(res==num)
                 break;
         }



         aa = String.valueOf(fat);

          if (fat == 100000){
             aa = "Não existe numero para esse resultado";
          }
             System.out.println("O numero do fatorial é: "+aa);

             System.out.println("");
             System.out.println("");


                     System.out.println("Digite 1 para calcular novamente ou 0 para sair");
                     a = ler.nextInt();




         }


     }

 }

The idea of the program is to do the inverse of the factorial, instead of entering a number and having the factorial result, if you type the result of the factorial, and you have the number that would arrive at this factorial. >

PS. The program works with a number of up to 9 digits.

    
asked by anonymous 12.06.2016 / 00:54

2 answers

1

In your example, replace the variable res with a BigInteger , like this:

BigInteger num = BigInteger.ONE;

And in the for loop does this:

for(fat=1;fat<=100000;fat++){
    num = num.multiply(BigInteger.valueOf(fat));
}

Pay attention not to abuse and use very high values.

    
13.06.2016 / 02:06
1

The long supports up to the value of -9,223,372,036,854,775,808 up to +9,223,372,036,854,775,807, that is, long accounts for 14 digits, supporting up to 19 digits.

Example

public static void main(String[] args) {
    long teste = Long.MAX_VALUE;
    System.out.println(teste);
    System.out.println("Algarismos suportados: " + String.valueOf(teste).length());
}

Output:

9223372036854775807
Algarismos suportados: 19

Example with BigInteger

public static void main(String[] args) {
    BigInteger teste = new BigInteger("9");
    BigInteger teste2 = new BigInteger("9");
    System.out.println(teste.add(teste2));
}

Output:

18
    
12.06.2016 / 23:52