views:

484

answers:

6

Hi All,

How to add two numbers of any length in java?

Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i right?

So if we want to add a number which is greater than this like below, i got a error

" Integer Number too large"

long a = 9223372036854775807L;
long b = 9223372036854775808L;

In C, we can take those numbers as char array, by traversing through the address of each char and use some data structure, we can add two numbers of any size.

How to do it java. Can we traverse through the address of each character in String.

+4  A: 

Check out the BigInteger class. It will be able to perform the operations you are looking for on really large numbers.

http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html

Sam Day
Not sure why I was rated down for my answer, given that the link provided is clearly the official java documentation, and all the information on that page is plenty for Manoj to determine how to use BigInteger.
Sam Day
Of course, it *is* java 1.4.2 documentation, which is pathetically old. (though I did not rate down for this) (though this is why I'm not rating up =) )
Vuntic
upvote for being the first with a relevant answer, but 1.4.2 is not really the 'official' documentation since it is quite old...
pstanton
I downvoted this answer because you just posted a link. In general, I think that an answer on SO should provide some general information before an Asker makes a jump to a link.
jjnguy
1.4.2 is still the first result on google <_<
poke
well maybe one or two humans here are smarter than google ...
seanizer
1.4.2 documentation is still relevant for BigInteger, it hasn't changed. Who cares. Stackoverflowers = nitpickersssssss :o
Sam Day
Added some content and removed my downvote.
jjnguy
@Justin: Thanks :)
Sam Day
@Sam, you are welcome. I hate being picky...i'ts just a bad habit.
jjnguy
+6  A: 

Use BigInteger. Here is an example.

Example code (based on above link) -

BigInteger reallyBig1 = new BigInteger("1234567890123456890");
BigInteger reallyBig2 = new BigInteger("2743534343434361234");
reallyBig = reallyBig.add(reallyBig2);
Gopi
Umm, why are there letters in the number?
jjnguy
@Justin :) typo in an attempt to create big numbers pressing random keys. Thanks for pointing it out. Good observation! corrected.
Gopi
Maybe you meant the second line to be `BigInteger reallyBig2 = new BigInteger("27435dfdsafasd61234",32);`.
MAK
Ahh, ok. Wasn't sure if you intended it of not.
jjnguy
+18  A: 

You can use a BigInteger.

BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("9223372036854775808");
BigInteger result = a.add(b);

The BigInteger will let you work with numbers of any size, but you lose a considerable amount of performance over long or int.

jjnguy
+1  A: 

The BigInteger will let you work with numbers of any size, but you lose a considerable amount of performance over long or int.

Actually, if you just need to run this operation once (user enters two numbers, and gets the result back), using BigInteger is fine. But if you need to perform the addition operation many times, you could use really your own implementation of big integer. When I was competing in ACM matches, we often used our own implementations based on char arrays (in C++). I suggest the following code. It is assumed that there are two arrays of integers, A and B. A[0] and B[0] store the lens of the corresponding numbers. A[i] and B[i] stores the digits themselves. A[1] and B[1] are the least significant digits. Therefore the number 1234 would correspond to such an array: {4,4,3,2,1}.

Now, suppose we want to sum these numbers and store them in array C in the same format. Here is an example of code, that you could use:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;
for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10;
  C[i] %= 10;
}
while (divisor>0) {
  C[++len] = divisor%10;
  divisor /= 10;
}
C[0] = len;

That code uses the simple rules of arithmetic addition and should work significantly faster than the BigInteger general implementation. Have fun with using that.

SPIRiT_1984
I'm being quoted! Hehe, good answer.
jjnguy
A: 

Hi All,

Thanks for your responses.

I have tried to code by passing the numbers as string and add each character from the end. It works fine for me.

Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on). Is the underlying mechanism of BigInteger is same as my code(add each character from end)?

Thanks.

Manoj
Please post updates to the question in the question itself by clicking on the edit link below the question.
abhin4v
Don't post a new question as answer, edit your original question instead. BigInteger is more efficient, because it uses an array of ints (longs?) and works on that, e.g. using the normal int addition but with "carry over". Multiplication is even more efficient, as there are algorithms like Karatsuba, which are faster than school multiplication.
Landei
A: 

Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on).

The difference is that you could use a larger radix, for example. Suppose the radix is 10000, not just 10. When the code of my previous answer would be modified like this:

int len1 = A[0],  len2 = B[0], divisor = 0;
int len = len1 >= len2 ? len1 : len2;

for (int i=1;i<=len;i++) {
  if (i>len1) C[i] = B[i]+divisor;
  else if (i>len2) C[i] = A[i]+divisor;
  else C[i] = A[i]+B[i]+divisor;
  divisor = C[i]/10000;
  C[i] %= 10000;
}
while (divisor>0) {
  C[++len] = divisor%10000;
  divisor /= 10000;
}
C[0] = len;

In that case the code runs 4 time faster (since there is no difference for the virtual machine in arithmetic operations, since they depend on the constant only). Also, this means, that the array of integers will be 4 times smaller. The only problem this causes is how to format the output.

SPIRiT_1984