Reputation: 45
How to store a huge number of nearly 100000 digits in C++?..
I have tried using long long int
and long double int
..Nothing worked for me..
Is there any other way to store such a huge number?
I wish to find the smallest palindrome larger than the given huge number.
Upvotes: 4
Views: 2386
Reputation: 11736
Upon further clarification in the comments section:
Yes, you can represent your number as a std::string in C++.
Here you find code for incrementing a number represented as a string:
#include <string>
#include <iostream>
#include <ostream>
void increment_numerical_string(std::string& s)
{
std::string::reverse_iterator iter = s.rbegin(), end = s.rend();
int carry = 1;
while (carry && iter != end)
{
int value = (*iter - '0') + carry;
carry = (value / 10);
*iter = '0' + (value % 10);
++iter;
}
if (carry)
s.insert(0, "1");
}
int main()
{
std::string big_number = "123456789012345678901234567899";
std::cout << "before increment: " << big_number << "\n";
increment_numerical_string(big_number);
std::cout << "after increment: " << big_number << "\n";
}
You can use this in a loop to increment your big number and check if the resulting string is a palindrome:
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
Edit
I do not claim this to be an efficient and correct solution to the problem. It's just a representation and incrementing method for big numbers.
Upvotes: 7
Reputation: 616
If you are feeling incredibly brave you could implement a long number as a linked list of individual integers. So that you could increment or also add, subtract, multiply and divide such numbers it would be a good idea to make a class and use operator overloading.
Upvotes: -1
Reputation: 31871
The GNU MP Bignum Library is a good solution. It is mainly a C library but has an effective C++ wrapper (with easy access to underlying C structures when needed). It has integer, rational, and floating point support.
Upvotes: 3
Reputation: 3736
You're looking for a 'bignum' or 'biginteger' library.
OpenSSL provides such a library, but it can be hard to use at times. Matt McCutchen's library seems much friendlier from an API standpoint.
Upvotes: 3