现在的位置: 首页 > 综合 > 正文

Leetcode Sqrt(x)

2014年04月05日 ⁄ 综合 ⁄ 共 529字 ⁄ 字号 评论关闭

Sqrt(x)

 Total Accepted: 8010 Total
Submissions: 37050
My Submissions

Implement int sqrt(int x).

Compute and return the square root of x.

分二分法和牛顿迭代法两种解法,详细请看:

http://blog.csdn.net/kenden23/article/details/14543521

二分法:

//2014-2-20 update		
	int sqrt(int x) 
	{
		double e = 0.0000001;
		double a = 0, b = x;
		double m = a + ((b-a)/2);
		double res = m*m - double(x);
		while (abs(res) > e)
		{
			if (res < 0) a = m+1;
			else b = m-1;
			m = a + ((b-a)/2);
			res = m*m - double(x);
		}
		return m;
	}

牛顿迭代法:

//2014-2-20 update		
	int sqrt(int x) 
	{
		if (x == 0) return 0;
		double xi1 = x, xi = 1;
		while (int(xi1) != int(xi))
		{
			xi = xi1;
			xi1 = (double(x)/xi + xi)/2;
		}
		return xi;
	}

抱歉!评论已关闭.