在j2me中,有時會用到開方運算,但是midp1.0中沒有提供該功能。這裡使用筆算開方的方式,實現了開任意數的n次方。這裡使用了long作為運算的臨時變數型別,在數值較大或者保留位數太多的時候,會出現因為long數值溢位而導致的錯誤。
public
class extract else
string result = "";
long a = 0;// 初值
long c = 0;// 差
long b = 0;// 嘗試的商值
int index = 0;
while (index < zhengshu.length)
}b = b - 1;
c = c - (power(10 * a + b, n) - power(10 * a, n));
a = a * 10 + b;
index++;
}result += a + ".";// 整數部分計算完畢
index = 0;
while (index < xiaoshu.length)
}b = b - 1;
c = c - (power(10 * a + b, n) - power(10 * a, n));
a = a * 10 + b;
index++;
}result += (a + 5) % power(10, baoliu + 1);// 這裡 a + 5 是為了實現四捨五入
result = result.substring(0, result.length() - 1);// 放棄最後1位
return result;
}/**
* 根據開方n的數值,將整數部分劃分成若干片段
* * @param str
* @param n
* @return
*/private
static string getzhengshu(string str, int n)
string zhengshu = new string[length];
for (int i = zhengshu.length - 1; i > 0; i--)
zhengshu[0] = str;
return zhengshu;
}/**
* 根據開方n的數值和保留的位數,將小數部分劃分成若干片段
* * @param str
* @param n
* @param decimaldigits
* @return
*/private
static string getxiaoshu(string str, int n, int decimaldigits)
string xiaoshu = new string[length];
for (int i = 0; i < xiaoshu.length; i++)
return xiaoshu;
}/**
* 得到乙個數的n次方
* * @param shu
* @param n
* @return
*/private
static
long power(long shu, int n)
return result;
}/**
* @param args
*/public
static
void main(string args) }
輸出結果是:
將3開2次方,保留3位小數:1.732
將3開5次方,保留3位小數:1.246
將3.08開2次方,保留3位小數:1.755
牛頓迭代法 求任意數的開n次方
牛頓迭代法是求開n次方近似解的一種方法,本文參考。假如 x n m 我們需要求x的近似值。感覺和物理做實驗一樣,先通過實驗觀察,再找出對應理論來解釋現象。這個演算法不是推導出來的,是首先通過觀察發現,再來證明推導,哈哈哈 以下結論都是建立在f x 二階可導的情況下成立。牛頓發現隨便找乙個曲線上的a點...
a的n次方優化
求a的n次方一般的最簡單的方式就是從頭乘到尾,但是這樣子時間時間複雜度較高 從頭乘到尾 o n private static long pow0 int a,int n return res 那我們應該如何優化呢?方法一 首先,我們是否可以使用二分法的思想,a的n次方等於a的n 2此方乘上a的n 2...
求a的n次方
此題面試時常有 解答方法有以下三種 1。直接迭代求解,這個很簡單,複雜度o n 1。分治法。複雜度 logn a a n 2 a an 1 如下 intpower inta intn 3.此方法複雜度為 n的二進位制表示中最高位1的index 原理為 事先建立a的 2m m為 0,x 的表。指導找到...