数据结构与算法分析 C 语言描述第二版第二章 欧几里得算法

数据结构与算法分析 C 语言描述第二版第二章——欧几里得算法

Given two numbers not prime to one another, to find their greatest common measure.

1. 算法讲解

见:Euclid’s Algorithm
Euclid’s algorithm works by continually computing remainders until 0 is reached. The last nonzero remainder is the answer.

2. 算法代码

书中采用迭代法。

unsigned int Gcd(unsigned int M, unsigned int N)
{
	unsigned int Rem;
	while (N > 0) {
		Rem = M % N;
		M = N;
		N = Rem;
	}
	return M;
}

3. 算法时间复杂度分析

需要用到的定理:

If M > N, then M mod N < M/2.

证明:

There are two cases. If N <= M/2, then since the remainder is smaller than N, the theorem is true for this case. The other case is N > M/2. But then N goes into M once with a remainder M - N < M/2, proving the theorem.

根据代码和定理做出如下推断:

变量:				M				N				Rem

初始值:				M				N				M%N

一次迭代后:          N			   M%N			   N%(M%N)

二次迭代后:        M%N		N%(M%N)		(M%N)%(N%(M%N) < (M%N)/2

结论:
After two iterations, the remainder is at most half of its original value. This would show that the number of iterations is at most 2log N = O(log N) and establish the running time.

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

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/103080578