Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
CodeRookie262 opened this issue Dec 29, 2020 · 1 comment
Open

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

CodeRookie262 opened this issue Dec 29, 2020 · 1 comment

Comments

@CodeRookie262
Copy link
Owner

No description provided.

@CodeRookie262
Copy link
Owner Author

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

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
Projects
None yet
Development

No branches or pull requests

1 participant