Seeking an efficient design of a fast algorithm for the n-th power of

topic

快速设计一个高效的求a的n次幂的算法

General algorithm

	// 时间复杂度O(n)
	private static int pow0(int a, int n) {
		int res = 1;
		for (int i = 0; i < n; i++) {
			res *= a;
		}
		return res;
	}

improve algorithm

public class a的n次幂 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int n = 15;
		int a = 2;
		int ans = pow(a, n);
		System.out.println(ans);
	}

	private static int pow(int a, int n) {
		if (n == 0) {
			return 1;
		}

		int res = a;
		int ex = 1;
		// 左移一位代表乘以2
		while ((ex << 1) <= n) {
			res *= res;
			ex <<= 1;
		}
		// 差n-ex次方没有去乘到结果里面
		return res * pow(a, n - ex);

	}

}

Published 60 original articles · won praise 4 · Views 1250

Guess you like

Origin blog.csdn.net/qq_43966129/article/details/105052342