| MIDP1.0不能使用浮點數(shù),因此這個算法只能計算正整數(shù)開方的整數(shù)部分,且算法中沒有任何乘法和除法運算,只有加減運算. 算法原理:1+3+5+...+(2n-1) = n^2
 根據(jù)公式我們要求X的開方,只需讓X-1,X-3,X-5....直到X為負數(shù),這時所有成功的次數(shù)就是平方根的整數(shù)部分.
 /*** @todo 計算正整數(shù)平方根的整數(shù)部分
 * @param x 要求平方根的正整數(shù)
 * @return 平方根的整數(shù)部分
 **/
 private int sqrt(int x)
 {
 int result = 0,j = 3;
 x--;
 while(x >= 0)
 {
 x -= j;
 j += 2;
 result++;
 }
 return result;
 }
 |