0

Is there any way I can preform calculations on numbers like 5000000000000000000000 in C++? I tried this:

#include<iostream>

using namespace std;

int main()
{
    unsigned long long int num1, num2;

    num1 = 50000000000000000;

    num2 = 50000000000000000;

    cout << num1*num2;
}

Any help?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ahmed
  • 1
  • You can try `std::uintmax_t` in `#include `. But it might not result in portable code. Beyond that you probably need a "Big Int" library. – François Andrieux Mar 31 '22 at 13:36
  • For example, Boost provides a multiprecision library: https://www.boost.org/doc/libs/1_74_0/libs/multiprecision/doc/html/index.html There are even some predefined integer types such as `int1024_t`: https://www.boost.org/doc/libs/1_74_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html. IIRC, it is header-only and it can optionally use some other MP libraries as backend. – Daniel Langr Mar 31 '22 at 13:38
  • depending on what you need to do you could use floating points. For the example in the question it would work quite well – 463035818_is_not_an_ai Mar 31 '22 at 13:39
  • [See boost calculate large factorials](https://stackoverflow.com/questions/67630357/c-factorial-of-number-100/67630658#67630658). – PaulMcKenzie Mar 31 '22 at 13:46

1 Answers1

2

is there any variable larger than unsigned long long int in C++

There are no standard integer types larger than unsigned long long. Floating point types have a larger range, but they lack precision in the range of high absolute values.

It is possible to make calculations with arbitrarily larger numbers by representing them with arrays where each elements is a "digit" of radix equal to the number of representable values of the element. Operations on such representation are called "arbitrary precision arithmetic". As for multiplication of arbitrary precision numbers, that is a well researched area. There are published algorithms such as the Schönhage–Strassen and Toom–Cook.

Such operations are not included in the standard library, but several open source implementations exist.

eerorika
  • 232,697
  • 12
  • 197
  • 326