3

So I have a programming assignment in which I have to work with 64 digit numbers. I am currently using the boost::multiprecision::cpp_int library but I'm not able to use it on large numbers.

For example-

#include <boost/multiprecision/cpp_int.hpp>

int main()
{
    boost::multiprecision::cpp_int n1 =123341257612045876129038576124390847381295732;   
}

This is giving the error that the code is too long. After experimentation, it seems like cpp_int (supposed to contain as large a number as you want) is acting like an unsigned long long (shown in the picture above), how do I solve this?

  • 2^64 = 1E19... your n1 there is much larger than that. Is multiprecision lib supposed to be able to do arbitrary precision arithmetic? – MFerguson May 04 '22 at 22:26
  • @MFerguson It's supposed to contain as large a number as you give it so this should work. I've also tried using int1024_t which has 1024 bits which should contain this number. But all of these are being interpreted as unsigned long longs. – Aayed Hassan May 04 '22 at 22:42
  • `123341257612045876129038576124390847381295732` is a numeric literal in C++ which cannot exceed `uintmax_t` range so obviously you can't use it for bigints if they're bigger than `uintmax_t`. You need to let `boost::multiprecision::cpp_int` parse the number from string – phuclv May 05 '22 at 00:35
  • duplicates: [big ints with boost : too large to be represented in any integer type](https://stackoverflow.com/q/64793676/995714), [Getting constant too big error while using boost library (cpp_int)](https://stackoverflow.com/q/61840403/995714) – phuclv May 05 '22 at 03:15

1 Answers1

6

Use the string constructor, because you cannot express the initializer in C++, otherwise.

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>

int main() {
    boost::multiprecision::cpp_int n1("123341257612045876129038576124390847381295732");
    n1 *= n1;
    n1 *= n1;

    std::cout << n1 << "\n";
}

Prints

231437371927256216552064578371685752056581253909626001052591740261122589692668963795268703088073326299461305156397520102373182511147316463882992573577585984095769469664077598976

Which is ~2.31 × 10^176

sehe
  • 374,641
  • 47
  • 450
  • 633