c++sqrt

find as many digits of the square root of 2 as possible


#include <iostream>
#include <cmath>

using namespace std;

int main()
{
 double a = sqrt(2);
 cout << a << endl;
}

hi this is the program to find sqrt of 2 it prints just 1.41421 in the output how to implement it in way such that it will print 200000 digits after decimal point

1.41421..........upto 200 000 digits

Is there any approach to print like this?


Solution

  • Here is the code for your question which using GNU GMP library. The code will print 1000 digits of sqrt(2), increase the number in the lines with comment to satisfy your request.

    #include <stdio.h>
    #include <gmp.h>
    
    int main(int argc, char *argv[])
    {
      mpf_t res,two;
      mpf_set_default_prec(1000000); // Increase this number.
      mpf_init(res);
      mpf_init(two);
      mpf_set_str(two, "2", 10);
      mpf_sqrt (res, two); 
      gmp_printf("%.1000Ff\n\n", res); // increase this number.
      return 0;
    }
    

    Please compile it with the following command:

    $gcc gmp.c  -lgmp -lm -O0 -g3