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 Apr 23 '15 at 00:19
-
2I doubt you could put anything inside a "unsigned long double"... – dtech Apr 23 '15 at 01:34
-
Another thought occurs - what is your 1000 digit number data source? Is it by chance a literal? – dtech Apr 23 '15 at 01:47
-
@ddriver. Yes, it's a literal. – wazalak Apr 23 '15 at 01: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 Apr 23 '15 at 02: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
-
-
1doesn't seem like it, but you may download it there and load it into your project, see here to get help with it http://stackoverflow.com/questions/10358745/how-to-use-libraries – sed Apr 23 '15 at 00:58
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

- 1,510
- 1
- 11
- 15
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.
-
That's not a bad approach for people learning C++, as a bit of a project, but a couple nit-picks: `num` has a `.size()` facility already so `digits` is redundant and another thing that could get out of sync, and a `std::vector
` or similar (even a `std::string`) would use a lot less memory. – Tony Delroy Apr 23 '15 at 03:47
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/

- 6,437
- 14
- 61
- 119
Depends on the usage.If you need to do computation on it, probably go with the Big Int Library. If not and only aim is storing, store it in an array with each digit stored in one array element.

- 95
- 1
- 2
- 12