C程序设计练习 01-幂运算

高效递归

对于偶数,xn=xn/2xn/2;对于奇数,xn=x(n-1)/2x(n-1)/2*x。时间复杂度为对数级。

long long foo(long long x, int n) {
	if (n == 0) {
		return 1;
	}
	if (n % 2 == 1) {
		return foo(x * x, n / 2) * x;
	}
	else {
		return foo(x * x, n / 2);
	}
}

位运算(快速求幂)

x21=x16+x4+x1,21的二进制表示为10101,可通过指数每次向右移一位来判断该位是否要乘上对应指数的幂。

long long foo(long long x, int n) {
	long long ans = 1;
	while (n) {
		if (n & 1) {
			ans *= x;
		}
		x *= x;
		n >>= 1;
	}
	return ans;
}

参考资料

Data Structure and Algorithm Analysis in C++(Fourth Edition), Mark Allen Weiss

posted @ 2021-01-02 23:21  埃利安里  阅读(64)  评论(0)    收藏  举报