2

Possible Duplicate:
How to implement big int in C++

For example, say I have a variable of the "long" type. A long can store values from -⁠9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Is it possible for me to create my own C++ data type that allows me to create integers of unlimited size? I know it's kind of reckless from a memory standpoint, but I'm just curious.

Community
  • 1
  • 1
Monkeyanator
  • 1,346
  • 2
  • 14
  • 29

3 Answers3

3

Ha! Here is a reckless answer!

Just create a class that dynamically creates and adds bit sets. To implement the class, you should create a vector (or any appropriate container you want/need) that store unsigned longs (each unsigned long represents a bit set of higher dimension than that of what precedes it; you can also use any POD types you want).

For the class to have virtually unlimited possible values, you should implement automatic detection (preferably on operators) for value overflows and underflows. For overflows you should then add a bit set of higher dimension after the last bit set. Underflows should be handled by setting a reference bit set that contains the value zero. If the value becomes lower than zero (or the lowest value), you should then add a bit set before the reference (or that which contains the lowest value) bit set.

Please read about binary arithmetic and base numbers. They should give you the idea (and are very useful indeed!).

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
  • Thank you, that was the type of comment I was looking for. This should help me very much on my science fair project, as I'm doing a program that is supposed to calculate extremely large prime numbers. When you said each unsigned long represents a bit set, you mean like maybe the first long would be 110111011101011010101110 and the second will be 1110111000001110010110101 as a continuation of the first set of bits? How would I convert this binary mess back into base 10 without the use of the default C/C++ primitives? Greate answer though :) – Monkeyanator Aug 24 '12 at 13:54
  • Sorry for the delay. Yes. You are absolutely right. You should read about base number conversions (binary to decimal) and on how to add numbers of different base dimensions. I can email you an example (or somewhat a tutorial) if you want. – Mark Garcia Aug 25 '12 at 03:05
  • Yes, that would be awesome. Sorry for the wait myself, my computer has been down for a while, I'm actually using a different computer right now. Yes, that would be great. My email is sammnaser@gmail.com – Monkeyanator Aug 30 '12 at 14:31
0

Sure, look eg at the GNU Multiple Precision Arithmetic Library.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
0

Yes, just implement it (or google). One example is http://sourceforge.net/projects/cpp-bigint/

Drakosha
  • 11,925
  • 4
  • 39
  • 52