Checking if a number is perfect square?

后端 未结 8 2055
野趣味
野趣味 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条回答
  •  猫巷女王i
    2021-02-10 01:50

    mmmm don't use float/double for your true/false outcome (you'll end up having approximation problems) Much better the integer apporach:

       boolean is_square(long long n)
       {
          long long a=n;
          while (a*a>n)
          {
             a=div(a+div(n,a),2);
          }
          return a*a==n;
       }
    

    div() is the integer division without remainder (you can use GCD() in some ways)

    I know, I know... care must be taken for overflow issues

提交回复
热议问题