Checking if a number is perfect square?

后端 未结 8 2056
野趣味
野趣味 2021-02-10 01:10

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          


        
8条回答
  •  故里飘歌
    2021-02-10 01:30

    You might use std::sqrt as a guess and test with multiplication:

    #include 
    #include 
    #include 
    
    bool isPerfectSquare(long long n){
        double guess = sqrt(n);
        long long r = std::floor(guess);
        if(r*r == n) return true;
        else {
            r = std::ceil(guess);
            return r*r == n;
        }
    }
    
    int main() {
        const long long Limit = std::pow(10, std::numeric_limits::digits10 / 2);
        std::cout << " Limit: " << Limit << '\n';
        for (long long i = 0; i < Limit; ++i) {
            if( ! isPerfectSquare(i*i)) {
                std::cout << "Failure: " << i << '\n';
                return 0;
            }
        }
        std::cout << "Success\n";
    }
    

提交回复
热议问题