C实现辗转相除法

目标:求最大公约数
方法:利用欧几里得算法(辗转相除法) 

思路:如果b=0,计算结束,a就是最大公约数否则,计算a除以b的余数,让a=b,而b=余数;回到第一步 。

非递归:

#include<stdio.h>
int main(){
	int a,b;
	int t;//余数 
	scanf("%d %d",&a,&b);
	printf("a=%d,b=%d,t=%d\n",a,b,a%b);
	while(b!=0){
		t=a%b;//必须a>b 
		a=b;//除数作被除数 
		b=t;//余数作除数 
		printf("a=%d,b=%d,t=%d\n",a,b,t);
	}
	printf("gcd=%d\n",a);
	return 0;
}

递归:

int gcd(int a,int b){
    if(b==0) return a;
    else return gcd(b,a%b);
} 

猜你喜欢

转载自blog.csdn.net/qq_41877184/article/details/89482739