Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with the sqrt() function in C++

Tags:

c++

c++17

So, I was writing code in C++, which required an intermediate step to check whether a number was a perfect square. I wrote the following code.

int sqrt_of_t = (int)sqrt(t);
if (sqrt_of_t*sqrt_of_t != t)
{
    cout << "NO" << endl;
}

This code gives the correct results in my system, but it fails when passing it through an online judge in Codeforces. The case where it fails doesn't have any overflow associated with it or anything (really small test cases). So, can anyone explain where it went wrong and suggest some alternate method to check if a number is a perfect square or not, which will work on all systems and not show behaviors like this. Here t is an int too.

like image 328
Vedanta Mohapatra Avatar asked Sep 01 '25 10:09

Vedanta Mohapatra


1 Answers

sqrt() returns a floating point number which you cast to int, which truncates any fractional part. The problem is that floating point cannot represent all integers exactly, so you may end up with something like 19.99999999999999 which you expect to be 20 but is actually 19 when cast to an integer.

To fix it, use rounding instead:

long sqrt_of_t = lrint(sqrt(t));
like image 83
John Zwinck Avatar answered Sep 03 '25 23:09

John Zwinck