cheapcoder's blog

By cheapcoder, history, 5 years ago, In English

The pow function in CPP gives output 1350851717672992000 for input pow(3, 38), but the correct output is 1350851717672992080 i.e. output differs by 89. So what is the issue?

Didn't find any solution on the net!! c++ version 7.4.0

pow(3, 38) ==> Correct output is 1350851717672992089, but the function gives output 1350851717672992000 which differs by 89.

Edit- Using the powl function worked! Thank you, everyone!!!

  • Vote: I like it
  • -29
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it +18 Vote: I do not like it

You realize that pow returns double or long double, and those types have limited precision?

»
5 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Do like this

unsigned long long res=1;
for(int i=0;i<38;i++) res * = 3;
cout<<res;

OR

Another function

But I don't think any contests problems ask us to print these huge answers generally they will be modulus some prime number.

  • »
    »
    5 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    powl is still a long double function. Never use it to exp whole numbers.

    • »
      »
      »
      5 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Ok. What about the first approach? Do we get any problem in the contest that ask us to calculate these huge numbers?

      • »
        »
        »
        »
        5 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Exponentation in loop is nice before big numbers come. It evaluates a^n in O(n), and binpow doing it in O(log n).

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Use binary exponentation. pow is function, that works with doubles, that have limited precision. So even if you call pow of two int or long arguments, it will evaluate it as doubles, and then round to int (ll). Same for squares. Never use pow(x,2), use x*x instead