141. Sqrt(x)【牛顿迭代法求平方根 by java】
生活随笔
收集整理的這篇文章主要介紹了
141. Sqrt(x)【牛顿迭代法求平方根 by java】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
Implement int?sqrt(int x).
Compute and return the square root of?x.
Example
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
Challenge
O(log(x))
題意:求給定數的平方根,如果用一般的方法,例如二分法之類的,需要考慮一下int型的范圍,別溢出。最好的方法時牛頓迭代法。代碼如下:
public class Solution {/*** @param x: An integer* @return: The sqrt of x*/public int sqrt(int x) {// write your code here//牛頓迭代法求平方根double p=2.0;double pre=0;while(Math.abs(p-pre)>1e-6){pre=p;p=(p+x/p)/2.0;}return (int)p;} }關于牛頓迭代法在平方根上的應用原理,參閱博客:?http://www.matrix67.com/blog/archives/361
轉載于:https://www.cnblogs.com/phdeblog/p/9097950.html
總結
以上是生活随笔為你收集整理的141. Sqrt(x)【牛顿迭代法求平方根 by java】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mzy,struts学习(一)
- 下一篇: Android LayoutInflat