I think there is a precision problem with the following code:
bool isPerfectSquare(long long n){
long long squareRootN=(long long)(sqrt(n)+0.5);
return squareRootN*squareRootN == n;
}
How to fix it? P.S: 1 <= n <= 10^10
Sqrt(4) could return 1.9999 => 1 so I added 0.5 so that it becomes 2 upon round off. Note: sqrt returns floating point.
This is an explanation that I found but still cant fix the code:
Hi, it seems you are also an victim of floating point values. If possible, you should always avoid floating point comparisons. It got worst with the increase in range of numbers. Say, when you assign float a=4.0 it is stored as 4.000...01111 or 3.999999...9978 or similar. So be cautious whenever you also type case a square root to an int. Possibility of these types of errors increases with the increase in the range of integer.
You use round
.
bool isPerfectSquare(long long n){
long long squareRootN=(long long)round((sqrt(n)));
if(squareRootN*squareRootN == n) {
return true;
}
else {
return false;
}
round
rounds the number to the nearest rounding. The function will be true only if n is a perfect square.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With