Tejas Jadhav
Tejas Jadhav

Reputation: 69

Print precise value of pow() function in c++

enter image description heremy output is coming wrong. I guess i'm wrong with casting. please help me out.

    int n;
    cin>>n;
    unsigned long long int a,s;
    cin>>a;
    s=(2*pow(10,n)+a);

But when I am giving large n like 17 or 18 then my output which is s is not coming as expected. see image for output e.g: when n=17, a=67576676767676788 then s=267576676767676800 which ideally should be 2*10^17 + 67576676767676788

Upvotes: 1

Views: 815

Answers (1)

Marek R
Marek R

Reputation: 37512

First you have to understand what is going on.

  1. To be able to use std::pow, compiler silently converts integer types to double and returned value is a double too.
  2. Note that double has 16 significant digits (in decimal representation).
  3. When you do assignment, conversion of double to long long int is silently performed
  4. unsigned long long int - if this type has 64 bits the maximum power of 10 is 19

Now if you want to exceed this limitation you should use an external library. gmp is quite nice.

If it is acceptable to have a limitation from range of unsigned long long int just implement your own power function.

Upvotes: 8

Related Questions