Skip to content

求一个数的平方根,精确到小数点后六位。 #11

Open

Description

@CodeRookie262
No description provided.

Activity

  1. CodeRookie262 commented on Dec 30, 2020

    @CodeRookie262
    OwnerAuthor

    可以采用二分法,获取最大,最小值,求他们的中间值的平方是否大于目标值,等于就直接返回,不等于则继续折半求中间值的平方直到接近目标值为止。

    var mySqrt = function(x) {
        let l = 0,
            h = x,
            p = x / 2,
            lp = p;
    
            if(x === 1 || x === 0) return x;
    
            do{
                if(Math.pow(p,2) > x){
                    h = p;
                }else if(Math.pow(p,2) < x){
                    l = p;
                }else{
                    return Math.floor(p);
                }
                lp = p;
                p = (l + h) / 2;
            }while(Math.abs(p - lp) >= Number.EPSILON);
    
            return Math.floor(p);
    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions