该题是用来公司教学,并无难度。用于说明算法效率差异以及循环和递归的效率差别。
package practice; import java.math.BigDecimal; /**
* @author caiyu
* @date 2014-12-3
*/
public class X_N_Square {
static BigDecimal x = new BigDecimal(7); public static void main(String[] args) {
int n = 1000;
BigDecimal result = x; long time = System.currentTimeMillis();
if (n < 5000)
for (int i = 1; i < n; i++) {
result = result.multiply(x);
}
System.out.println(System.currentTimeMillis() - time); if (n < 5000)
System.out.println(result); time = System.currentTimeMillis();
result = cal(n, x);
System.out.println(System.currentTimeMillis() - time); if (n < 5000)
System.out.println(result); time = System.currentTimeMillis();
// 换底公式
int count = (int) Math.floor(Math.log(n) / Math.log(2));
result = x;
while (count-- > 0) {
result = (n >> count) % 2 == 0 ? result.multiply(result) : result
.multiply(result).multiply(x);
}
System.out.println(System.currentTimeMillis() - time); if (n < 5000)
System.out.println(result);
} public static BigDecimal cal(int n, BigDecimal r) {
if (n == 1)
return x;
if (n % 2 == 0) {
r = cal(n / 2, r);
return r.multiply(r);
} else {
r = cal((n - 1) / 2, r);
return r.multiply(r).multiply(x);
}
} }