1、求最大公约数
求公约数的规则如下
/*** M % N = 0 : N*gcd(M, N) =* M % N = R, R > 0 : gcd(N, R)*/
2、代码实现
#include <stdio.h>
/*** M % N = 0 : N*gcd(M, N) =* M % N = R, R > 0 : gcd(N, R)*/int gcd(int M, int N)
{if (M <= 0 || N <= 0)return 0;int result = M % N;return result == 0 ? N : gcd(N, result);
}int main()
{int result = gcd (18, 12);printf("result is %d\n", result);return 0;
}
3、运行结果
1111deMacBook-Pro:dabian a1111$ gcc -g gcd.c -o gcd
1111deMacBook-Pro:dabian a1111$ ./gcd
result is 6