How to create a very large BigInteger

2019-07-06 11:05发布

问题:

I need to add two very big integers

  46376937677490009712648124896970078050417018260538
+ 37107287533902102798797998220837590246510135740250;

What's wrong with this?

BigInteger f = 37107287533902102798797998220837590246510135740250;

How I can solve this problem in Java using BigInteger?

回答1:

The problem here is that 3710... will be interpreted as an int, and so it will be out of range. Essentially what you're trying to do is to create an int, and then convert it to a BigInteger, and the first step of this will fail because an int can't store a number that large.

You need to use the constructor that takes a String:

BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

and similarly for your other BigInteger, of course.



回答2:

Java does not have built-in support for BigInteger literals - you cannot write this:

BigInteger f = 37107287533902102798797998220837590246510135740250;

Use the constructor of BigInteger that takes a String instead:

BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

To add two BigInteger objects:

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

BigInteger sum = f.add(g);


回答3:

you need to construct your BigInteger from a String, not a numerical literal, as this cannot work as it is converted to an int first.



回答4:

Try add method like:

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

BigInteger's object needs to be created using new operator and you are trying to assign number directly as bigInteger which is no a valid statement. You could pass that number as a string to BigInteger's constructor as above.



回答5:

You should write the statement as

BigInteger f = new BigInteger("37107287533902102798797998220837590246510135740250");

BigInteger g = new BigInteger("46376937677490009712648124896970078050417018260538");

Now, for addition

BigInteger sum = f.add(g);

For multiplication

BigInteger product = f.multiply(g);

And so on.

You can't use +,-,*,/ operators in case of BigIntegers unlike other variable types. You need to use methods for each of the operations.