理论公式
具体代码
#include <stdio.h>
/*
递归函数
*/
int Gcd(int n,int m){
if(n<0||m<0){ //错误
return -1;
}
if(m==0){ //递归出口
return n;
}else if(m>n){
return Gcd(m,n);
}else{
return Gcd(m,n%m);
}
}
/*
循环函数
*/
int Gcd2(int n,int m){
int tn,tm,temp;
if(n<0||m<0){
return -1;
}
if(m>n){ //交换参数位置
tn = m;
tm = n;
}else{ //不交换
tn = n;
tm = m;
}
while(tm!=0){
temp = tn;
tn = tm;
tm = temp%tm;
}
return tn;
}
void main(void){
int x,y;
do{
printf("请输入你要求最大公约数的两个数(负数退出):");
int n,m;
scanf("%d%d",&n,&m);
x=n;
y=m;
printf("(递归调用)%d和%d的最大公约数是:%d\n",n,m,Gcd(n,m));
printf("\n");
printf("(循环函数)%d和%d的最大公约数是:%d\n",n,m,Gcd2(n,m));
printf("\n\n");
}while(x>=0||y>=0);
getch();
}