Swap Long for Biginteger or Bigdecimal?

Asked

Viewed 823 times

2

I am trying to read from the keyboard a very large integer number, I saw that there are the type Biginteger or Bigdecimal, I do not know if they are bigger than the Long.

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

could 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 typing a number and having the factorial result, if you type the factorial result, and you have the number that would reach this factorial.

PS. The program works with numbers up to 9 digits.

2 answers

2


In this example, replace the variable res by a BigInteger, thus:

BigInteger num = BigInteger.ONE;

And in the loop for do so:

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

Pay attention not to abuse and use very high values.

1

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 the 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());
}

Exit:

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));
}

Exit:

18

Browser other questions tagged

You are not signed in. Login or sign up in order to post.