zeds
zeds

Reputation: 137

How to create a very large BigInteger

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?

Upvotes: 3

Views: 2658

Answers (5)

Amrit Kumar Muduli
Amrit Kumar Muduli

Reputation: 21

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.

Upvotes: 1

Jesper
Jesper

Reputation: 206796

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);

Upvotes: 3

SMA
SMA

Reputation: 37023

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.

Upvotes: 1

chiastic-security
chiastic-security

Reputation: 20520

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.

Upvotes: 14

mnagel
mnagel

Reputation: 6854

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.

Upvotes: 1

Related Questions