美文网首页
x的平方根

x的平方根

作者: AustinWeii | 来源:发表于2018-11-25 14:01 被阅读0次

描述
实现 int sqrt(int x) 函数,计算并返回 x 的平方根。

样例
sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

挑战
O(log(x))

 * @param x: An integer
 * @return: The sqrt of x
 * n = t * t
 * n + t * t = 2 * t * t
 * (n / t) + t = 2 * t
 * t = (n / t + t) / 2
 */ 
const sqrt = function (x) {
    if (x==0) return 0;
    var i=1;
    while(Math.abs(x-i*i)>1.0){
        i=parseInt((x/i+i)/2);
    }
    return i;
}

相关文章

网友评论

      本文标题:x的平方根

      本文链接:https://www.haomeiwen.com/subject/aphpqqtx.html