C语言——求最大公约数(浙大翁恺教授C语言入门第五周3,2求最大公约数)

思路

//用辗转相除法求最大公约数
/*
如果b等于0,计算结束,a就是最大公约数;
否则,计算a除以b的余数,让a等于b,而b等于那个余数;
回到第一步

a b t
12 18 12
18 12 6
12 6 0
6 0
计算结束,a就是最大公约数
*/

代码

//用辗转相除法求最大公约数 
/*
如果b等于0,计算结束,a就是最大公约数;
否则,计算a除以b的余数,让a等于b,而b等于那个余数;
回到第一步 

a      b      t
12    18     12
18    12     6
12    6      0
6     0     
计算结束,a就是最大公约数 
*/ 
#include<stdio.h>
int main()
{
    
    
	
	int a,b;
	int t ;
	printf("请您输入两个数: ");
	scanf("%d %d",&a,&b);
	
	while(b!=0) 
	{
    
    
		t=a%b;
		a=b;
		b=t;
	}
	printf("最大公约数=%d\n",a); 

	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_57495651/article/details/132284790