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

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

I participated in a recent contest, wherein I submitted this solution for the Multiplication table problem.

My solution passed the pretests but failed on a TC in system testing. In the failed TC, I was printing the square root of a perfect square and it was printed as 1e9 instead of 1000000000.

The square root function was not printing in scientific notation for smaller numbers, but it did for sqrt(1e18) i.e. 1e9. Does anyone know why this happened?

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

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

This behavior is due to cout rather than sqrt().

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

    Why does this happen with cout? Do you know any reason for this?

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

      cout by default outputs in scientific notation for large float numbers. Use
      cout << fixed; for fixed point notation.

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

To overcome the problem you can typecast the result into long long , eg., typedef long long ll; ll n = 1e18; ll num = sqrt(n); cout << num << endl;

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

std::sqrt returns a double, not an int. When numbers in doubles are printed, larger numbers are printed in scientific notation. To print it precisely, you have to typecast it into an int.

Also, it is better to use std::sqrtl instead of sqrt, because sqrt sometimes fails with numbers upto $$$10^{18}$$$.