Euclid's algorithm 是求 Greatest Common Divisor 的。 Euclid's algorithm 利用最大公约数的性质,对两个数之进行减法和交换运算,最后判断0之外没有任何其他操作了,非常适合计算机运算。 那好看看C语言的实现:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/* */
/* Implementation of Euclid's algorithm1 */
/* Programmed by Lee jaekyu */
/* */
#include <stdio.h>
int get_gcd(int u, int v)
{
int t;
while(u)
{
if (u<v)
{
t=u; u=v; v=t;
}
u=u-v;
}
return v;
}
void main (void)
{
int u,v;
puts ("\n EUCLID : Get GCD of two positive integer"
"\n Input 0 to end program ");
while(1)
{
puts ("\n Iput two positive integer
![](https://www.cnblogs.com/Images/dot.gif)
scanf("%d %d", &u,&v);
if (u<0 ||v<0)
continue;
if (u==0 || v==0)
break;
printf("\n GCD of %d and %d is %d.", u, v, get_gcd(u,v));
}
}
运行结果:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
rize@rize-laptop ~/Algorithm-C> gcc -o euclid_GCD euclid_GCD.c
euclid_GCD.c: In function ‘main’:
euclid_GCD.c:22: warning: return type of ‘main’ is not ‘int’
rize@rize-laptop ~/Algorithm-C> ls
euclid_GCD* euclid_GCD.c
rize@rize-laptop ~/Algorithm-C> ./euclid_GCD
EUCLID : Get GCD of two positive integer
Input 0 to end program
Iput two positive integer
![](https://www.cnblogs.com/Images/dot.gif)
45 90
GCD of 45 and 90 is 45.
Iput two positive integer
![](https://www.cnblogs.com/Images/dot.gif)
3 98
GCD of 3 and 98 is 1.
Iput two positive integer
![](https://www.cnblogs.com/Images/dot.gif)
34 89
GCD of 34 and 89 is 1.
Iput two positive integer
![](https://www.cnblogs.com/Images/dot.gif)
0 0
rize@rize-laptop ~/Algorithm-C>