Test of perfect square using Newton-Raphson (accepted)


  • 0
    P
    public bool IsPerfectSquare(int num) {
        //newton raphson f(x1)=x0-(f(x0)/fprime(x0))
        // f(x)=x^2-n
        if(num<=0){return false;}
        int xk=num;
        int xk1=((xk+(num/xk))>>1);
        while(Math.Abs(xk1-xk)>1)
        {
            xk=xk1;
            xk1=((xk+(num/xk))>>1);
        }
        return ((xk1*xk1)==num);
    }

  • 0

    Accepted? Amazing... I can't even find the question of your answer. Where is the question "Test of perfect square"?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.