I think most people would recommend using a professional big number library such as http://gmplib.org/
However, if your goal is to do it yourself as an exercise then there are many options.
I'm not sure what your code does exactly, but any floating point type representation will only give you the first few digit values. Usually, the goal is to obtain
all of the digits.
My own best effort produces a big integer value in a linked list, with 8 digits stored in each node.
To calculate a factorial I use an overload for bigInt *= unsigned int
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
bigInt_sList& bigInt_sList::operator*=(unsigned int x)
{
node* iter = head;
long long unsigned int prod = 0;
unsigned int carry = 0;
while( iter )
{
prod = iter->dgt;
prod *= x;
prod += carry;
carry = prod/base;
iter->dgt = prod%base;
iter = iter->next;
}
if( carry > 0 )// one more term
{
tail->next = new node( carry, NULL );
tail = tail->next;
numDigits += digitsPerNode;
}
return *this;
}
|
Then I use it in this function to calculate a factorial.
1 2 3 4 5 6 7 8 9
|
bigInt_sList factorial( unsigned int n )
{
bigInt_sList z(1);
if( n < 2 ) return z;
for( unsigned int x = 2; x <= n; ++x )
z *= x;
return z;
}
|
This will find 2,000! in well under a second.
One drawback with this singly linked list method is that, since the digits are stored from least to most significant in the list, I must use recursion in the 'to string' conversion for displaying the number.
Try searching this site for examples of other big integer codes. You should find many.