cheapcoder's blog

By cheapcoder, history, 7 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?
»
7 years ago, hide # |
 
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?

»
7 years ago, hide # |
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.

»
7 years ago, hide # |
 
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