给定两个正整数,求它们的最大公约数,对于这个算法想必大家都已经知道,解决这个问题最经典的方法是采用欧几里德算法,据说这是历史上最早的算法。
#include <stdio.h>
#include <stdlib.h>
#define max(a,b) (a) > (b) ? (a) : (b)
#define min(a,b) (a) < (b) ? (a) : (b)
/*
INPUT: m,n (m >0 ,n>0)
OUTPUT: -1 error, else the common divisor of m and n
*/
int G*C*D(int m,int n)
{
int a = max(m,n);
int b = min(m,n);
int remainder = 1;
if( m<=0 || n<=0 )
{
return -1;
}
while(remainder > 0)
{
remainder = a % b;
a = b;
b = remainder;
}
return a;
}
int main(int argc, char* argv[])
{
int first,second,result;
if(argc != 3)
{
fprintf(stderr,"There should be two number/n");
exit(-1);
}
first = atoi(argv[1]);
second = atoi(argv[2]);
result = G*C*D(first,second);
if(result != -1)
{
printf("The common divisor of %d and %d is %d/n",first,second,result);
}
else
{
printf("m and n should be greater than 0/n");
}
return 0;
}