How can you write code in c ++ so that when outputting N ^ 2 with N = 72, the output is not 4.72237e + 021 but 4722366482869645213696

3 answers 3

If we are talking about the value of 2 72 , then it can be represented exactly in floating binary arithmetic like IEEE 754. Even a 32-bit floating type is enough. If your platform is built on such arithmetic and implements it qualitatively, then you just need to perform the calculation in a floating type and output the result in the format fixed

 #include <cmath> #include <iostream> #include <iomanip> int main(int argc, const char * argv[]) { float x = std::pow(2.0f, 72.0f); std::cout << std::fixed << std::setprecision(0) << x << std::endl; } 

http://coliru.stacked-crooked.com/a/d97961ea4de0df0b


If desired, it will not be difficult to simply implement a long integer calculation and translate back into a decimal notation, as was done for this task: Sum of digits of the number 100! . For example, based on the second approach from my answer

http://coliru.stacked-crooked.com/a/c63bb623f4605835

Although to solve this problem by cyclic multiplication by 2 is a huge waste.

    You can display something, but all the numbers will not be accurate ... For example,

     unsigned long long v = 43697122555ull; int main(int argc, const char * argv[]) { double x = v; x = x*x; cout << x << endl; cout << fixed << setprecision(0) << x << endl; } 

    will output (VC ++ 2017)

     1.90944e+21 1909438519586689646592 

    while true value is

     1909438519586689728025 

    So I don’t see much point in this conclusion. Well, do not give double desired accuracy ...

      First, the number shown is = 2 ^ 72 (two to seventy-second degrees), and not vice versa.

      Secondly, the size of such a number, which occupies 72 bits, exceeds the size of the available primitive integer types - 64 bits, therefore for calculations with absolute precision (ie, not with double) and to display you will need a library for working with long arithmetic, for example , GMP (now the browser swears on their site as phishing) or MPIR.

      If you need only simple operations - addition, multiplication - then you can do it yourself, and there are examples for SO ( random fresh )