package Chapter2; public class Two_twentytwo { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(fun(2, 16)); } /** * 快速求X^a * @param X * @param a * 思路:2^i < a, (2^(i+1)>a),先求2-2^i这段的乘积,然后看a到2^i的距离和a到2^(i+1)的距离哪个近,用哪个循环补上 */ public static long fun(long X, int a) { int i; int pre = 0; int times = 0; long XX = X; for(i=2; i<=a; i *= 2) { X *= X; pre = i; times++; } if((a-pre)< (i-a)) { for(int j=0; j<(a-pre); j++) { X*=XX; times++; } }else if((a-pre) > (i-a)) { for(int j=0; j<(i-a); j++) { X*=XX; times++; } } System.out.println(times); return X; } }