How can I perform operations with large numbers that cannot be stored in one variable

In Java, I would like to be able to do operations with really large integers (which cannot be stored in long), how can I do this?

What is the best way to handle this, with good performances? Should I create my own data type that contains several long variables?

Example:

public class MyBigInteger{
    private long firstPart;
    private long secondPart;

   ...
}

public MyBigInteger add(long a, long b){
    MyBigInteger res;

    // WHAT CAN I DO HERE, I guess I could do something with the >> << operators, but I've never used them!

    return res;
}

Thank!

+3
source share
5 answers
import java.math.BigInteger;

public class BigIntegerTest {

    public BigInteger add(long a, long b){
        BigInteger big1 = new BigInteger(Long.toString(a));
        BigInteger big2 = new BigInteger(Long.toString(b));

        return big1.add(big2);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new BigIntegerTest().add(22342342424323423L, 234234234234234234L));
    }

}
+6
source

You should check out the BigInteger java class . He does exactly what you need.

+9
source

If you really need high performance, BigInteger / BigDecimal is not going to cut it. I used the apfloat library and it worked very well for me.

+1
source

If the numbers are really long, I would suggest storing them in a linked list (each node is a digit) or in a file (in this case, the io access delay will be there), and then enter the digit by digit, which we did manually in our 2nd class.

0
source

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


All Articles