Checking if a number is perfect square?

后端 未结 8 2025
野趣味
野趣味 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:33

    The code is fine!

    I have taken the time to write a small test. As the input range is limited, we can simply validate the function for every input.

    Not that I did have to add an explicit cast to double for the sqrt function for it to compile. (using MS VC++ 10)

    #include 
    #include 
    #include 
    
    bool isPerfectSquare(long long n){
        long long squareRootN=(long long)(sqrt((double)n)+0.5);
    
        return squareRootN*squareRootN == n;
    }
    
    
    int main()
    {
        // for the input range,
        // generate a set with numbers that are known to be perfect squares.
        // all the rest are not.
        std::set perfectSquares;
        for(long long i = 1ll; i <= 100000ll; ++i) {
            perfectSquares.insert(i*i);
        }
        std::cout << "Created lookup." << std::endl;
    
        // now test the function for all the numbers in the input range   
        int progress = -1;
        for(long long i = 1ll; i <= 10000000000ll; ++i) {
            bool expected = (perfectSquares.count(i) == 1);
            bool actual = isPerfectSquare(i);
    
            if(expected != actual) {
                std::cout << "Failed for " << i << std::endl;
            }
    
            int newprogress = i / 100000000ll;
            if(newprogress != progress) {
                progress = newprogress;
                std::cout << "Progress " << progress << "%" << std::endl;
            }
        }
        std::cout << "Test finished." << std::endl;
    }
    

    Results? Pass for all values! The problem must be in the code that uses the function. Maybe add input range validation to the function.

提交回复
热议问题