1、编写递归函数求两个正整数a
和b
的最大公约数(GCD,Greatest Common Divisor),使用Euclid算法:
-
如果
a
除以b
能整除,则最大公约数是b
。 -
否则,最大公约数等于
b
和a%b
的最大公约数。
Euclid算法是很容易证明的,请读者自己证明一下为什么这么算就能算出最大公约数。最后,修改你的程序使之适用于所有整数,而不仅仅是正整数。
#include<stdio.h>
/*GCD of a and b*/
int gcd (int a,int b)
{
if (a<0)
{a=-a;}
if (b<0)
{b=-b;}
/* if ( a < b )
{ int c = a ;
a = b ;
b = c ;
}*/
int c = a % b ;
if (c!=0)
{
a = b;
b = c;
int result=gcd ( a,b );
return result;
}
else
{
int result = b;
return result;
}
}
int main()
{
int a,b;
printf("please enter a and b:");
scanf("%d%d",&a,&b);
if ( a*b==0 )
{
printf("ERROR!!!\nThe number you put can't be 0!\n");
return 0;
}
int result=gcd(a,b);
printf("The GCD of %d and %d is %d\n",a,b,result);
return 0;
}
转载请注明源地址:http://blog.csdn.net/whorus1/article/list/2,谢谢!