How to create a very large BigInteger

I need to add two very large integers

  46376937677490009712648124896970078050417018260538
+ 37107287533902102798797998220837590246510135740250;

      

What's wrong with that?

BigInteger f = 37107287533902102798797998220837590246510135740250;

      

How can I solve this problem in Java using BigInteger

?

+3


source to share


5 answers


The problem here is what 3710...

will be interpreted as int

and therefore it will be out of range. Essentially, you are trying to create int

and then convert it to BigInteger

, and the first step of that will fail because it int

cannot store a number that is large.

You need to use a constructor that takes String

:



BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

      

and similarly for your other of BigInteger

course.

+13


source


Java doesn't have built-in support for BigInteger

literals - you can't write this:

BigInteger f = 37107287533902102798797998220837590246510135740250;

      

Use a constructor BigInteger

that takes instead String

:



BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

      

To add two objects BigInteger

:

BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");
BigInteger g = new BigInteger("46376937677490009712648124896970078050417018260538");

BigInteger sum = f.add(g);

      

+3


source


you need to build your BigInteger from a string, not a numeric literal, as this can't work as it converts to int first.

+1


source


Try adding a method like:

BigInteger number1 = new BigInteger("46376937677490009712648124896970078050417018260538");
BigInteger number2 = new BigInteger("37107287533902102798797998220837590246510135740250");
BigInteger sum = number1.add(number2);

      

The BigInteger object must be created using a new operator and you are trying to assign the number directly as bigInteger, which is not a valid operator. You can pass this number as a string to the BigInteger constructor as above.

+1


source


You should write the instruction as

BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

BigInteger g = new BigInteger("46376937677490009712648124896970078050417018260538");

      

Now, to add

BigInteger sum = f.add(g);

      

To multiply

BigInteger product = f.multiply(g);

      

Etc.

You can not use the operators +

, -

, *

, /

in the case of BigIntegers unlike other types of variables. You need to use methods for each of the operations.

+1


source







All Articles