求两个数的最大公约数 c语言 gcd
#include<stdio.h>
void swap(int *pnum1,int *pnum2)
{
int t;
t=*pnum1;
*pnum1=*pnum2;
*pnum2=t;
}
int gcd(int num1,int num2)
{
int r;
if(num1<num2)
swap(&num1,&num2);
while(num2!=0)
{
r=num1%num2;
num1=num2;
num2=r;
}
return num1;
}
int gcd_recursive(int num1,int num2)//gcd_(a,b)=gcd(b,a%b)
{
if(num1<num2)
swap(&num1,&num2);
if(num2==0)
return num1;
else
return gcd_recursive(num2,num1%num2);
}
int main()
{
int num1,num2;
num1=12;
num2=16;
printf("%d和%d的最大公约数为:%d\n",num1,num2,gcd_recursive(num1,num2));
return 0;
}