Блог пользователя cheapcoder

Автор cheapcoder, история, 5 лет назад, По-английски

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!!!

  • Проголосовать: нравится
  • -29
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится +18 Проголосовать: не нравится

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

»
5 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

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

    • »
      »
      »
      5 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

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

      • »
        »
        »
        »
        5 лет назад, # ^ |
          Проголосовать: нравится 0 Проголосовать: не нравится

        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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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