How to calculate and display large numbers in java

How could I calculate and display all digits of large numbers, like 9999! (factorial 9999) in java?

Look at this url that calculates 9999! and selects all the numbers.

+5
source share
5 answers

Use BigInteger; 9999! took 120 ms with Java 8. Here is a version that uses longs, and half that time:

 public static BigInteger factorial(int n) { // Try first to use longs in calculating the factorial. BigInteger result = BigInteger.ONE; long factor = 1; for (int i = n; i > 1; --i) { if Long.MAX_VALUE / factor < i) { // Overflow? result = result.multiply(BigInteger.valueOf(factor)); factor = i; } else { factor *= i; } } return result.multiply(BigInteger.valueOf(factor)); } 
+4
source

Use BigInteger, its limit is your memory

 public static BigInteger factorial(BigInteger num) { if (num.compareTo(new BigInteger("1")) < 0) { return new BigInteger("1"); } else { return factorial(num.subtract(new BigInteger("1"))).multiply(num) ; } } 
+7
source

The Java standard library provides the BigInteger class, which can be unlimited integer values ​​(in fact, they are limited, but only by available memory).

+4
source

Not the fastest, but not very slow.

 public static BigInteger factorial(int n) { BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) { result = result.multiply(BigInteger.valueOf(i)); } return result; } 
+2
source

You can use strings (yes, don't be surprised, you can!). A program can be created in lines to multiply two very large numbers (here I say that the numbers say 5000 digits in length, each!) I already created them for addition and subtraction, and it’s not so difficult to create it for Multiplication, and I assure you that although you will think that using BigInteger will be faster, but using Strings will be Ultrafast compared to BigInt.

And what slipped through my middle, I used the StringBuilder class to make the program more efficient.

+1
source

Source: https://habr.com/ru/post/1207889/


All Articles