Chinaunix首页 | 论坛 | 博客
  • 博客访问: 964265
  • 博文数量: 58
  • 博客积分: 10192
  • 博客等级: 上将
  • 技术积分: 1845
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-22 21:24
文章分类

全部博文(58)

文章存档

2011年(11)

2010年(12)

2009年(20)

2008年(15)

分类:

2011-08-28 20:56:30

本文的copyleft归gfree.wind@gmail.com所有,使用GPL发布,可以自由拷贝,转载。但转载请保持文档的完整性,注明原作者及原链接,严禁用于任何商业用途。
作者:gfree.wind@gmail.com
博客:linuxfocus.blog.chinaunix.net
  

今天开始重新学习算法,以一个简单的算法题目开始吧。
使用Euclidean算法计算最大公约数。先介绍一下Euclidean算法。下面是来自wiki的介绍
The GCD of two numbers is the largest number that divides both of them without leaving a remainder. The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the smaller number is subtracted from the larger number. For example, 21 is the GCD of 252 and 105 (252 = 21 × 12; 105 = 21 × 5); since 252 − 105 = 147, the GCD of 147 and 105 is also 21. Since the larger of the two numbers is reduced, repeating this process gives successively smaller numbers until one of them is zero. When that occurs, the GCD is the remaining nonzero number. 
就是说两个数的最大公约数,等于两数之差与较小数的最大公约数。

下面是C代码的实现
  1. unsigned int get_greatest_common_divisor(unsigned int u, unsigned int v)
  2. {
  3.     unsigned int t;
  4.     while (u > 0) {
  5.         if (u < v) {
  6.             t = u;
  7.             u = v;
  8.             v = t;
  9.         }
  10.         u = u-v;
  11.     }

  12.     return v;
  13. }
在《Algorithms in C》的课后题中,要求计算3个数的最大公约数。这个解答仍然可以通过上面计算两个数的最大公约数的函数来实现。如有abc三个数,分别求出ab的最大公约数d,然后再计算d与c的最大公约数。
  1. unsigned int get_greatest_common_divisor_of_two_num(unsigned int u, unsigned int v)
  2. {
  3.     unsigned int t;
  4.     while (u > 0) {
  5.         if (u < v) {
  6.             t = u;
  7.             u = v;
  8.             v = t;
  9.         }
  10.         u = u-v;
  11.     }

  12.     return v;
  13. }

  14. unsigned int get_greatest_common_divisor_of_three_num(unsigned int x, unsigned int y, unsigned z)
  15. {
  16.     unsigned int a = get_greatest_common_divisor_of_two_num(x, y);
  17.     
  18.     return get_greatest_common_divisor_of_two_num(a, z);
  19. }
在网上还可以搜到一种通过取模来求取GCD的算法,而且也说是Euclid算法。这让我很困惑啊。。。怎么会有两种说法呢?不过还是以英文为主吧。所以还是认为Euclid算法是通过这个减法来求取GCD吧,这个要比取模运算高效。


参考:《Algorithms in C》
阅读(1344) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~