Is there any way to store a 1000 digit number in c++? I tried storing it to an unsigned long double but it is still to large for its type.
- 1Many ways. Search for "big int library" here or on the web.Drew Dormann– Drew Dormann2015-04-23 00:19:46 +00:00Commented Apr 23, 2015 at 0:19
- 2I doubt you could put anything inside a "unsigned long double"...dtech– dtech2015-04-23 01:34:35 +00:00Commented Apr 23, 2015 at 1:34
- Another thought occurs - what is your 1000 digit number data source? Is it by chance a literal?dtech– dtech2015-04-23 01:47:15 +00:00Commented Apr 23, 2015 at 1:47
- @ddriver. Yes, it's a literal.wazalak– wazalak2015-04-23 01:52:00 +00:00Commented Apr 23, 2015 at 1:52
- Well, it won't work, C++ doesn't support literals of such size. IIRC big number libs usually input the numbers as strings rather than number literals.dtech– dtech2015-04-23 02:19:51 +00:00Commented Apr 23, 2015 at 2:19
5 Answers
You may find your answer here How to store extremely large numbers? GMP answer sounds right, ie this is what it does with pi digits https://gmplib.org/pi-with-gmp.html
2 Comments
You have to implement it yourself or use a library for it. In particular I love GMP: https://gmplib.org/ , which is an C implementation of Big Int/Float and has C++ wrapper
Comments
Use a custom class for your number, something like this:
#include <vector> #include <iostream> class large_num { private: int digits; // The number of digits in the large number std::vector<int> num; // The array with digits of the number. public: // Implement the constructor, destructor, helper functions etc. } For a very large number just add each digit to the vector. For example if the number if 123456, then you do num.pushback(); In this case push all the digits 1,2, .. 6. You can store a extremely large numbers this way.
1 Comment
num has a .size() facility already so digits is redundant and another thing that could get out of sync, and a std::vector<int8_t> or similar (even a std::string) would use a lot less memory.You should try this one
http://sourceforge.net/projects/libbigint/
great library for things like this.
also you can use boost.
http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/intro.html
also one of the most commons is
https://gmplib.org/