GCD (greatest common divisor)【求最大公约数】
来源:互联网 发布:c51单片机 定时器计时 编辑:程序博客网 时间:2024/05/20 05:28
The following snippet is copied from the book(Structure and Interpretation of Computer Programs 1.2.5)
-----------------------------------------------
The greatest common divisor (GCD) of two integers a and b is defined to be the largest integer that divides both a and b with no remainder.
The idea of the algorithm is based on the observation that, if r is the remainder when a is divided by b, then the common divisors of a and b are precisely the same as the common divisors of b and r. Thus, we can use the equation
GCD(a,b) = GCD(b,r)
to successively reduce the problem of computing a GCD to the problem of computing the GCD of smaller and smaller pairs of integers. For example,
GCD(246,40) = GCD(40,6)
= GCD(6,4)
= GCD(4,2)
= GCD(2,0)
= 2
reduces GCD(206,40) to GCD(2,0), which is 2. It is possible to show that starting with any two positive integers and performing repeated reductions will always eventually produce a pair where the second number is 0. Then the GCD is the other number in the pair. This method for computing the GCD is known as Euclid's Algorithm.42
--------------------------------------------------
The following code works in VC2005
#include "stdafx.h"
#include <stdio.h>
/*
function: gcd
input: a,b
output: the gcd of integer a and b
*/
int gcd(int a, int b)
{
if(0 == b)
{
return a;
}
else
{
return gcd(b, a%b);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int r = gcd(206, 40);
printf("r=%d", r);
r = gcd(40, 206);
printf("r=%d", r);
return 0;
}
remark: Euclid's Algorithm: 欧几里得算法
- GCD (greatest common divisor)【求最大公约数】
- 求最大公约数Greatest Common Divisor(GCD)
- Euclid Greatest Common Divisor-GCD - 欧几里得 最大公约数
- The greatest common divisor gcd(最大公约数)
- 最大公约数GCD(Greatest Common Divisor)算法小结
- 最大公约数Greatest Common Divisor
- GCD (Greatest Common Divisor)
- Eculid算法递归地求解GCD(Greatest Common Divisor,最大公约数)
- 最大公约数(greatest common divisor)算法
- 最大公约数(Greatest Common Divisor)
- GCD Algorithm(Greatest Common Divisor)
- common divisor---求最大公约数
- Greatest Common Divisor 最大公约数 O(n)
- Greatest Common Divisor 欧几里得算法(最大公约数)
- Greatest Common Divisor(GCD) of Two Numbers
- Greatest Common Divisor (GCD) - Euclidean algorithm
- More than one way to get gcd(greatest common divisor,最大公约数)
- Greatest Greatest Common Divisor
- socket编程原理
- 开篇
- SKYEYE 学习
- asdfasdf
- 进程间通信(四):利用邮槽
- GCD (greatest common divisor)【求最大公约数】
- 进程间通信(三):利用命名管道
- STL实践指南(1)
- Alpha混合物体的深度排序[译]
- 进程间通信(二):利用匿名管道
- AfxGetApp用法
- 从用友软件看国内的软件开发的前景
- 进程间通信(一):利用剪贴板
- windows 2003 server的一些优化设置