Description:
请实现下面两个函数,分别完成对两个数求最大公约数,和求一个数阶乘的求解。
要求:两个函数都需要递归实现求解,否则本题按0分处理。主函数已给出如下:
#include<stdio.h>
// function declares here, first is Greatest common divisor, next is factorial.
int gcd(int m, int n);
int fac(int p);
int main(void) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("%d %d\n", gcd(a, b), fac(c));
}
// next is function's defintion.
你只需要利用递归实现这两个函数。
ps: 强烈建议大家课后可以看看期中测试题目的Maxmal Discount那道题的答案。(学习递归函数的运用,合并排序,指针,内存管理)
因为所写的内容比较少,避免误判为抄袭,请各位为你的函数多写注释。
Hint:
最大公约数:辗转相除法。
阶乘:按定义求解即可。
#include<stdio.h>
// function declares here, first is Greatest common divisor, next is factorial.
int gcd(int m, int n) {
if (n % m == 0)
return(m);
else
return (gcd(n%m, m));
}
int fac(int p) {
if (p == 0 || p == 1)
return(1);
//是0或者1就返回1
else
return(p * fac(p - 1));
//p*已知p-1的阶乘
}
int main() {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("%d %d\n", gcd(a, b), fac(c));
return 0;
}
// next is function's defintion.