euler1's blog

By euler1, history, 5 years ago, In English

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?

  • Vote: I like it
  • +4
  • Vote: I do not like it

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

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

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

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

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

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

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

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 years ago, # |
  Vote: I like it +10 Vote: I do not like it

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}$$$.