Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure should I use for BigInt class

I would like to implement a BigInt class which will be able to handle really big numbers. I want only to add and multiply numbers, however the class should also handle negative numbers.

I wanted to represent the number as a string, but there is a big overhead with converting string to int and back for adding. I want to implement addition as on the high school, add corresponding order and if the result is bigger than 10, add the carry to next order.

Then I thought that it would be better to handle it as a array of unsigned long long int and keep the sign separated by bool. With this I'm afraid of size of the int, as C++ standard as far as I know guarantees only that int < float < double. Correct me if I'm wrong. So when I reach some number I should move in array forward and start adding number to the next array position.

Is there any data structure that is appropriate or better for this?

like image 747
user1086004 Avatar asked Mar 30 '12 12:03

user1086004


People also ask

What is the datatype for BigInt 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 you declare BigInt in C++?

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

Is BigInteger a data type?

The BIGINT data type stores integers from -(2 63 -1) to 2 63 -1, which is –9,223,372,036,854,775,807 to 9,223,372,036,854,775,807, in eight bytes. This data type has storage advantages over INT8 and advantages for some arithmetic operations and sort comparisons over INT8 and DECIMAL data types.


2 Answers

So, you want a dynamic array of integers of a well known size?

Sounds like vector<uint32_t> should work for you.

like image 67
Joni Avatar answered Nov 15 '22 00:11

Joni


As you already found out, you will need to use specific types in your platform (or the language if you have C++11) that have a fixed size. A common implementation of big number would use 32bit integers and ensure that only the lower 16 bits are set. This enables you to operate on the digits (where digit would be [0..2^16) ) and then normalize the result by applying the carry-overs.

like image 34
David Rodríguez - dribeas Avatar answered Nov 14 '22 23:11

David Rodríguez - dribeas