题解 | #阶乘#
阶乘
https://www.nowcoder.com/practice/e58c8a55162d49c48115bdfa5da7da56
看到是递归题我就点进来了,很快啊!
规律好找,4的奇数阶乘和与3一样,偶数和在3的基础上加4!就行……一直缩小规模就到1了,n是0时弹出
找一个数记录上一次阶乘值,这次要加到和里面就再用这个数乘n,避免重复计算阶乘
#include<stdio.h> void calculate(int n, int* y1, int* y2, int* lastnum) { if (n == 0) { return; } else if (n % 2 == 0) { //只区分奇偶 calculate(n - 1, y1, y2, lastnum); *lastnum *= n; *y2 += *lastnum; } else { calculate(n - 1, y1, y2, lastnum); *lastnum *= n; *y1 += *lastnum; } } int main() { int n; while (scanf("%d", &n) != EOF) { //4,奇数等于3,偶数等于3+4!…… //y1、y2分别记录奇偶和,lastnum记录上一次阶乘值 int y1 = 0, y2 = 0, lastnum = 1; calculate(n, &y1, &y2, &lastnum); printf("%d %d\n", y1, y2); } return 0; }