[LeetCode][JavaScript]Sqrt(x)

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

https://leetcode.com/problems/sqrtx/


对于数学早就还给老师的我,开方真是跪了。

查了一下是牛顿迭代法(什么鬼。

先随便猜一个数,我就猜了三分之一,然后套用公式。

candidate = (candidate + x / candidate) / 2;

题目要求返回int型,我精度就算到了0.01。

查牛顿迭代法的途中看到一篇文章很有意思。

http://www.guokr.com/post/90718/

 1 /**
 2  * @param {number} x
 3  * @return {number}
 4  */
 5 var mySqrt = function(x) {
 6     var candidate = x / 3;
 7     while(Math.abs(x - candidate * candidate) > 0.01){
 8         candidate = (candidate + x / candidate) / 2;
 9     }
10     return parseInt(candidate);    
11 };
原文地址:https://www.cnblogs.com/Liok3187/p/4601173.html