Hi all,

Recently I was solving problem Sad Powers. In the editorial of the problem it is mentioned that sqrt() function of c++ has some precision issues. On using the function in my problem on some value gives me wrong answer. After looking others solution I observed that some have used additional checks. e.g. If square root of value x is required then many solutions have checked for both x and (x-1) /(x+1). I could not understand why that additional check is required.

Can anybody please tell why this additional check is required or what are the issues with sqrt() function?

Thanks!!

Remember that sqrt() has 4 type of parameters two of them is sqrt(double x) and sqrt(long double x). If you feed the parameter with long long type, the function will call sqrt(double x). Which means you will losing precision if the long long number > +- 10^14 because of the precision of double type holds.

You want to use the one with long double type as it will hold the precision of long long number AND the floating point (as good as doubles are).

To use it, simply call it by typecast the number to long double such as sqrt(1.0L * x).

You can look at my submission for example (I just recently solved it too).

Thanks for your advice!! Will keep that in mind next time.

Floating points will always have precision errors — avoid them if you can.

E.g instead of ceil(n/k)

something like (n%k==0? n/k : n/k+1 )

Assuming that n and k are integers, I think (n+k-1)/k is more common.

It may lead to overflow when n and k are big integers.

You can use (n-1)/k+1 instead.

That is ceil not floor.

this is what happens when you type things on the phone

ceil(1.0*n / k), will give correct result.

C++ has a builtin sqrtl that is much more precise than sqrt.

Use sqrtl(),it is more precise.