分享林福平老师上课所讲的基础程序
/*
* 作者:太原理工大学 计算机学院 林福平* 说明:本程序根据有关书籍内容或网络上的程序编辑修改而成。
* 程序力求做到最为简洁地实现有关算法。
*
* 计算两个数的最大公约数三种算法程序
*
*/
#include <stdio.h>
#define DEBUG
#ifdef DEBUG
int c1=0, c2=0, c3=0;
#endif
int gcd1(int, int);
int gcd2(int, int);
int gcd3(int, int);
void swap(int *, int *);
int main(void)
{
int m=42, n=140;
if(m>n)
swap(&m,&n);
printf("gcd1: %d %d result=%d\n", m, n, gcd1(m, n));
printf("gcd2: %d %d result=%d\n", m, n, gcd2(m, n));
printf("gcd3: %d %d result=%d\n", m, n, gcd3(m, n));
#ifdef DEBUG
printf("c1=%d c2=%d c3=%d\n", c1, c2, c3);
#endif
return 0;
}
/* 递归法:欧几里得算法,计算最大公约数 */
int gcd1(int m, int n)
{
#ifdef DEBUG
c1++;
#endif
return (m==0)?n:gcd1(n%m, m);
}
/* 迭代法(递推法):欧几里得算法,计算最大公约数 */
int gcd2(int m, int n)
{
if(m==0)
return n;
while(m>0)
{
#ifdef DEBUG
c2++;
#endif
int c = n % m;
n = m;
m = c;
}
return n;
}
/* 连续整数试探算法,计算最大公约数 */
int gcd3(int m, int n)
{
if(m==0)
return n;
int t = m;
while(m%t || n%t)
{
#ifdef DEBUG
c3++;
#endif
t--;
}
return t;
}
void swap(int *pm, int *pn)
{
int temp;
temp = *pm;
*pm = *pn;
*pn = temp;
}