数据结构与算法分析 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值