+ 1

C++ Large Numbers?

How can I store large numbers with several digits in c++? I've read about using vectors to do this, but I can't figure it out. Can someone give me an example of how I would achieve this? Like, for example, say I'd want to store 2^1000. That number is too large right? Is there another way to store it?

30th Mar 2019, 3:48 PM
Daniel Cooper
Daniel Cooper - avatar
4 Respostas
+ 2
Can you give me an example? I want to understand how it would work. You don't need to use large numbers, just use small ones. I want to make sure I'm understanding this correctly.
30th Mar 2019, 4:57 PM
Daniel Cooper
Daniel Cooper - avatar
+ 2
Let me add an example of my own: https://code.sololearn.com/cV3o3NWxVZ11/?ref=app
30th Mar 2019, 6:21 PM
HonFu
HonFu - avatar
+ 1
You could use vectors, you could use strings, whatever you want. vectors are more efficient, but it's harder to implement and to print the final result. I think you need to implement division/modulus for that which isn't the easiest thing. Don't quote me on that one though. It's just what the biginteger library does. strings are the opposite, not efficient but easy to handle and print the results. How you do it is just like you learned in school, 1 digit at a time. Multiplication for example you pretty much just translate these steps into code: --24 --83 * --__ --72 1920 + ____ 1992 Same thing for addition, subtraction and division. Although there are more efficient algorithms out there. Implementing a correct biginteger library is a challenge on its own though. I think I got away with the barebone multiplication method for project euler #16, you don't need the addition part cause you only deal with 1 digit if you constantly multiply by 2. But if you don't feel like it, which is understandable, you can use an existing library, and possibly, read through its code: https://mattmccutchen.net/bigint/ Either that or just use ruby which has a build-in biginteger class where you can do it within just a few lines, not trivial in C++.
30th Mar 2019, 4:09 PM
Dennis
Dennis - avatar
+ 1
Sure, here is one that does addition ( doesn't handle negatives ) https://code.sololearn.com/cXmookpkGN02/?ref=app I also happen to have one for bit shifting, which also could be used for project euler #16 cause powers of 2 can be calculated using bit shifting. ( also no negatives ) https://code.sololearn.com/cN12Tm8Wh80D/?ref=app
30th Mar 2019, 5:52 PM
Dennis
Dennis - avatar