Blog Stats
Posts - 53
Articles - 4
Comments - 59
Trackbacks - 0
News
我使用新博客啦:
http://www.linjunhai.com/
大家到我的新博客上看看吧!
隨筆分類
(28)
JAVA天地(17)
其它相關(11)
文章分類
(4)
心情日志(4)
隨筆檔案
(53)
2011年5月 (2)
2011年4月 (1)
2011年3月 (1)
2010年12月 (1)
2010年9月 (1)
2010年8月 (1)
2010年5月 (1)
2010年3月 (1)
2009年11月 (1)
2009年10月 (1)
2009年7月 (1)
2009年5月 (2)
2009年1月 (2)
2008年12月 (11)
2008年11月 (2)
2008年10月 (1)
2008年9月 (1)
2008年7月 (3)
2008年6月 (1)
2007年10月 (1)
2007年8月 (1)
2007年7月 (3)
2007年4月 (1)
2007年3月 (3)
2006年12月 (4)
2006年11月 (5)
文章檔案
(4)
2007年5月 (2)
2007年4月 (2)
相冊
我的相冊
相關鏈接
Alvin's Blog
我現在使用的新博客.
CSS3 中文手冊
簡單實用的在線 CSS3 中文手冊
Scripts 學盟
不再悲催,體驗編寫腳本的樂趣!
給我留言
BlogJava 的留言板不用了, 用這個啦.
林俊海的博客
超級大菜鳥,每天要自強!
[JAVA]大數開平方(模擬手算的方法)
在 CSDN 看到的问题。 要求算出开平方结果的精确整数部分
想了想,想不到别的好的方法 就用了摸拟手算的方法
public static void main(String[] args) { System.out.print("sqrt(1)=" + sqrt("1")); System.out.print("\tsqrt(25)=" + sqrt("25")); System.out.print("\tsqrt(26)=" + sqrt("26")); // sqrt(26)==5 呵呵,因为只有整数部分 System.out.print("\tsqrt(100)=" + sqrt("100")); System.out.println("\tsqrt(144)=" + sqrt("144")); // 生成一个 5000 位以内的数 StringBuffer sb = new StringBuffer(""); Random rand = new Random(); int length = rand.nextInt(5000)+1; for (int i=0; i<length; i++) sb.append(rand.nextInt(10)); String theNumber = sb.toString(); System.out.println("n:" + sb.toString()); System.out.println("位数:" + length); // 开方 long t = System.currentTimeMillis(); BigInteger result = sqrt(theNumber); t = System.currentTimeMillis()-t; System.out.println("sqrt(n)=" + result.toString()); System.out.println("用时:" + t + "毫秒"); } public static BigInteger sqrt(String theNumber) { int length = theNumber.length(), i; BigInteger res = BigInteger.ZERO; BigInteger twenty = BigInteger.valueOf(20); BigInteger t, x=BigInteger.ZERO, v, few=BigInteger.ZERO; BigInteger hg = BigInteger.valueOf(100); String tmpString = null; int pos = 2-length%2; tmpString = theNumber.substring(0, pos); while (true) { v = few.multiply(hg).add(BigInteger.valueOf(Integer.parseInt(tmpString))); if (res.compareTo(BigInteger.ZERO)==0) i=9; else i = v.divide(res.multiply(twenty)).intValue(); for (; i>=0; i--) { t = res.multiply(twenty).add(BigInteger.valueOf(i)).multiply(BigInteger.valueOf(i)); if (t.compareTo(v)<=0) { x = t; break; } } res = res.multiply(BigInteger.TEN).add(BigInteger.valueOf(i)); few = v.subtract(x); pos++; if (pos>length) break; tmpString = theNumber.substring(pos-1, ++pos); } return res; }
posted on 2009-05-21 03:55
林俊海
閱讀(1045)
評論(0)
編輯
收藏
新用戶注冊
刷新評論列表
只有注冊用戶
登錄
后才能發表評論。
網站導航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
Powered by:
.Text
and
ASP.NET
- Copyright © 林俊海
主站蜘蛛池模板:
司法
|
三原县
|
延川县
|
贵定县
|
吉林省
|
达日县
|
根河市
|
收藏
|
泰宁县
|
汉源县
|
噶尔县
|
射洪县
|
罗江县
|
铜山县
|
上虞市
|
锡林郭勒盟
|
永泰县
|
新乐市
|
乐业县
|
象山县
|
临潭县
|
上饶市
|
哈巴河县
|
遂宁市
|
西和县
|
建昌县
|
景德镇市
|
化州市
|
永胜县
|
娄烦县
|
藁城市
|
建昌县
|
平潭县
|
威海市
|
红原县
|
中山市
|
宜川县
|
理塘县
|
磐安县
|
富锦市
|
东乡族自治县
|