Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8018063
  • 博文数量: 159
  • 博客积分: 10424
  • 博客等级: 少将
  • 技术积分: 14615
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-14 12:45
个人简介

啦啦啦~~~

文章分类
文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(10)

2011年(116)

2010年(22)

分类: C/C++

2011-08-25 23:18:09

本文的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》
阅读(8869) | 评论(18) | 转发(2) |
给主人留下些什么吧!~~

love_wisdom2011-10-17 10:25:16

比如有人喜欢动脑子, 可以给这些人开发动脑子和学习的游戏.

GFree_Wind2011-09-25 20:17:36

love_wisdom: 建议找一本数论教科书和习题集,比如在当当网上可以找到。.....
现在我不知道数论,会对我的计算机水平有多少帮助?我知道如果作为搞研究的,肯定是有用的,但是对于来说并不需要搞研究,不知道帮助有多大呢

love_wisdom2011-09-25 16:32:32

建议找一本数论教科书和习题集,比如在当当网上可以找到。

love_wisdom2011-09-25 16:27:16

binary euclidean algoritham
and
extended euclidean algorithm
and
bezout theorem

GFree_Wind2011-08-29 23:17:00

blacksapper: 效率问题就不知道了。复杂度应该是线性的。O(n)
内存不知道。
三个数。假设是10 20 30,先求10和20的最大公约数:10再用最大公约数和30求最大公约数还是10。就是.....
理解,已经修改了。但是没有必要使用递归