0

In C, you can perform a simple:

int a = b + c;

Now, if a is larger than 2^32 (or maybe it's 2^31+1), you'd change the code to:

long a = b + c;

or

unsigned long a = b + c;

But how would you implement addition like:

bigint a = b + c;

where bigint is some sort of class/typedef/structure for storing and computing large integers (numbers that are hundreds of digits long). If you were just trying to add numbers together using a standard, hand-written decimal approach from elementary school, you can do infinitely long numbers in the equation. But come around to Computer Science, how can you use a binary, efficient approach where you can do infinitely long computations (provided enough RAM is available)

More so, is there a way of doing this that isn't terribly slow?

bobbybee
  • 1,758
  • 1
  • 16
  • 27

3 Answers3

0

You can use a bigint library, or if you really feel ambitious, you can create a dynamic array to store your integers.

jh314
  • 27,144
  • 16
  • 62
  • 82
0

There are very fast ways to do this (tough still slower than math in CPU registers, mind you). Libraries for this already exist, but if you are interested in the implementation details I would suggest inspecting the source code of GMP (http://gmplib.org/), as well as reading (and doing the exercises in) Knuth's The Art of Computer Programming, Volume 2: Seminumerical Algorithms.

CmdrMoozy
  • 3,870
  • 3
  • 19
  • 31
0

"More so, is there a way of doing this that isn't terribly slow?"

Compared to fixed length, 16, 32, 64 and in some machines, 128-bit, it will ALL be quite slow, because the math has to be done in small steps. Addition and subtraction isn't too bad, just one or two clock-cycles per unit in the array (32 or 64 bit depending on architecture), but multiplication and division does get quite slow. As numbers get significantly large (more than a few thousand digits or so), you also run into problems of cache-misses, which slows the calculation.

But you can certainly get a bit better than storing digits in a ascii string.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227