Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a solution for Java's limitation in calculating and storing big numbers

Tags:

java

in python with a simple loop you can calculate, let's say 600! it's a very very big number but python can easily take care of it in a fraction of a second.even it's more than 200 digit long. in java in the other hand you are bound to 64bit literals (long data type). so the machine will return 0.
is there any way to overcome this?

like image 941
Confuzzeled David Avatar asked Jul 30 '13 08:07

Confuzzeled David


People also ask

How do you add a large number in Java?

math. BigInteger. add(BigInteger val) is used to calculate the Arithmetic sum of two BigIntegers. This method is used to find arithmetic addition of large numbers of range much greater than the range of biggest data type double of java without compromising with the precision of the result.

When to use BigInteger in Java?

BigInteger represents immutable arbitrary-precision integers. It is similar to the primitive integer types but allows arbitrary large values. It is used when integers involved are larger than the limit of long type. For example, the factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000.

Is BigInteger bigger than long?

3. BigInteger Larger Than Long. MAX_VALUE. As we already know, the long data type is a 64-bit two's complement integer.


1 Answers

You can use the Java BigInteger class.

And a simple example:

import java.math.BigInteger;  BigInteger k = BigInteger.valueOf(10000L); k = k.pow(10000); //k is now 10000^10000  System.out.println(k.toString()); 

It's important to know that the class is immutable. You can also look into the similar BigDecimal class for arbitrary precision signed decimal numbers.

like image 87
Kon Avatar answered Sep 28 '22 09:09

Kon