Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a number is perfect square?

Tags:

c++

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.

like image 641
Sahil Sareen Avatar asked Oct 20 '22 08:10

Sahil Sareen


1 Answers

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.

like image 139
Emi987 Avatar answered Oct 27 '22 09:10

Emi987