Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data-structure should I use to create my own "BigInteger" class?

As an optional assignment, I'm thinking about writing my own implementation of the BigInteger class, where I will provide my own methods for addition, subtraction, multiplication, etc.

This will be for arbitrarily long integer numbers, even hundreds of digits long.

While doing the math on these numbers, digit by digit isn't hard, what do you think the best datastructure would be to represent my "BigInteger"?

At first I was considering using an Array but then I was thinking I could still potentially overflow (run out of array slots) after a large add or multiplication. Would this be a good case to use a linked list, since I can tack on digits with O(1) time complexity?

Is there some other data-structure that would be even better suited than a linked list? Should the type that my data-structure holds be the smallest possible integer type I have available to me?

Also, should I be careful about how I store my "carry" variable? Should it, itself, be of my "BigInteger" type?

like image 615
Fifa89 Avatar asked Feb 08 '10 19:02

Fifa89


People also ask

How do you declare BigInteger in C++?

BigInt a = Integer(string); BigInt a = Integer(char[]); BigInt a = Integer(int); BigInt a = Integer(long long);

Is BigInteger a class in Java?

Class BigInteger. Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.

How do I create an array of BigInteger in Java?

BigInteger class provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations. BigInteger bInteger = new BigInteger(arr); The following is an example that creates BigInteger from a byte array in Java.


2 Answers

Check out the book C Interfaces and Implementations by David R. Hanson. It has 2 chapters on the subject, covering the vector structure, word size and many other issues you are likely to encounter.

It's written for C, but most of it is applicable to C++ and/or Java. And if you use C++ it will be a bit simpler because you can use something like std::vector to manage the array allocation for you.

like image 177
finnw Avatar answered Sep 19 '22 20:09

finnw


Always use the smallest int type that will do the job you need (bytes). A linked list should work well, since you won't have to worry about overflowing.

like image 21
captncraig Avatar answered Sep 21 '22 20:09

captncraig