1!+2!+。。。+20!用递归算法怎么写啊
收起
知与谁同
2018-07-22 14:21:03
2477
0
4
条回答
写回答
取消
提交回答
-
用C语言写的
# include<stdio.h>
int fac(int n)
{
long y;
if (n == 0 || n == 1)
y = 1;
else
y = n*fac(n-1);
return y;
}
main()
{
int i = 1, n;
long sum = 0;
printf("input n:\n");
scanf("%d", &n);
for (; i <= n; i++)
sum = sum+fac(i);
printf("%ld\n", sum);
}
2019-07-17 22:54:35
-
如果这题只能用c语言还要递归,不好办哦
至今没看到这个题用c语言写对的
2019-07-17 22:54:35
-
/* 计算前N项大数阶乘和的递归实现 */
/* 大数用一般整型存储会造成数据溢出,产生错误,需用数组保存 */
#include <stdio.h>
#include <string.h>
// 计算大数的阶乘
void fac(int b, char *result) {
if (1 == b) return;
char *p = result;
int t, m=0;
while(*p) {
t = (*p - '0') * b + m;
*p++ = t % 10 + '0';
m = t / 10;
}
while (m) {
*p++ = m % 10 + '0';
m /= 10;
}
*p = '\0';
fac(b-1, result);
}
// 大数求和
void big_sum(char *sum, char *num) {
int m = 0, t = 0;
while (*sum && *num) {
t = *sum + *num - 2 * '0' + m;
*sum = t % 10 + '0';
m = t / 10;
++sum; ++num;
}
char *p = *sum > *num ? sum : NULL, *q = sum;
if (!p) while(*sum++ = *num++);
p = q;
while (*p) {
t = *p - '0' + m;
*p++ = t % 10 + '0';
m = t / 10;
}
while (m) {
*p++ = m % 10 + '0';
m /= 10;
}
*p = '\0';
}
// 初始化保存结果的数组
void Init_R(char *result) {
int i = 0;
while (*result)
*result++ = (i++ == 0) ? '1' : 0;
}
const int SIZE = 20; // 前n项的大小
const int MAXSIZE = 1000; // 最大阶乘结果位
const int INC = MAXSIZE / 10; // 求和结果位增量
int main()
{
char r[MAXSIZE] = {'1'};
char sum[MAXSIZE + INC] = { 0 };
// 计算前N项阶乘和
for (int i = 1; i <= SIZE; ++i) {
fac(i, r);
big_sum(sum, r);
Init_R(r);
}
// 打印字符串"1+2+...+n="
for (int i = 1; i <= SIZE; ++i)
printf("%s%d!", i == 1 ? "" : "+", i);
printf("=\n");
// 逆序从高位开始输出最后求和结果
int index = strlen(sum);
while (index--)
printf("%c", sum[index]);
printf("\n");
return 0;
}
2019-07-17 22:54:35
-
public class Test {
public static void main(String[] args) {
int sum=0;
for (int i = 1; i <= 20; i++) {
sum+=fac(i);
}
System.out.println(sum);
}
public static int fac(int n){
if (n==1) {
return 1;
}else {
return n*(n-1);
}
}
}
2019-07-17 22:54:35