数据结构与算法分析 C 语言描述第二版第二章 取幂运算

数据结构与算法分析 C 语言描述第二版第二章 取幂运算

计算 XN

递归算法:

long int Pow(long int x, unsigned int N) 
{
	if (N == 0)
		return 1;
	if (ISEVEN(N))
		return Pow(X * X, N / 2);	
	else
		return Pow(X * X, N / 2) * X;
}

算法思想:折办递归,时间复杂度分析类似二分查找。

时间复杂度分析:

We will count the number of multiplications as the measurement of running time.

line 3 to 4 handle the base of the recursion. Otherwise, if N is even, we have : XN = XN/2 * XN/2 , and if N is odd, XN = X(N-1)/2 * X(N-1)/2.

The number of multiplication required is clearly at most 2logN, because at most two multiplications (if N is odd) are required to halve the problem.

Line 8 can also be rewritten as

return Pow(X, N-1) * X;

without affecting the correctness of the program. Because the sequence of the multiplications is the same as before.

说明:
原来第8行计算:如果 N 是奇数,则一直执行第六行,每次 N/2 都还是基数,但每次都要计算两次乘积。

第二种方案:如果 N 是奇数,执行新第8行使 N -1 变成偶数,再将 N 减半,此时 N 又变成基数,因此需要执行乘积才会减半,所以时间复杂度同上面情况相同。

如果不用这种递归减半的算法,普通算法需要 N - 1 次乘积,见下面程序:

long int Pow(long int X, unsigned int N)
{
	lont int sum = 1;
	for (int i = 1; i <= N; i++) {
		sum *= X;
	}
	return sum;
}

这种的时间复杂度是 O(N),比递归用的时间长。

发布了120 篇原创文章 · 获赞 2 · 访问量 5809

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/103089581
今日推荐