0

How can you represent integer arithmetic for numbers larger than what a 32 or 64 bit processor allows. I'm trying to write a small Java calculator, and the input would have to be a string of numbers that would then have to be converted into either a binary or base-10 representation. It would then have to be added, multiplied, divided, or subtracted from another string of numbers that would also have to be converted. Obviously languages like Python and Ruby can handle things like "9999999999999999999" + "999999999999999999". But I am uncertain as to a method of doing so from a Java standpoint.

I've started out by defining a new class with a constructor that can parse whether the string is actually a string of numbers. As to convert them into binary or base-10 and how is something that I can do, but I'm lost as to which one would be more beneficial down the road when I add methods to this class like add, subtract, multiply, and divide.

Any conceptual ideas, big or small are helpful. Thanks in advance!

crashprophet
  • 327
  • 1
  • 4
  • 13

2 Answers2

3

Take a look at the BigInteger and BigDecimal classes. Both are arbitrary-precision implementations. As such, they obviously have a much larger (and non-constant) overhead than number literals. As the names would imply, BigInteger is only used for integers, while BigDecimal can store any rational decimal number.

Additionally, they can sometimes be a pain to work with because Java does not support operator overloading, so you can't use Java's math operators. Use the class's methods instead.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
1

Try using BigInteger class. It is designed to handle large numbers.

Amir Kost
  • 2,148
  • 1
  • 16
  • 30