当前位置 : 主页 > 编程语言 > c语言 >

【算法】求n!,求1!+2!+...+(n-1)!+n!

来源:互联网 收集:自由互联 发布时间:2023-08-25
1、求阶乘 n! int main() {int i, n, ret;printf("输入n的值:");scanf("%d", n);ret = 1;for (i = 1; i = n; i++) {ret = ret * i;}printf("n!= %d",ret);return 0;} 2、求阶乘之和 n!+(n-1)!+...+1! int main() {int i, j, n, ret, sum;pr

1、求阶乘 n!

int main() {

	int i, n, ret;

	printf("输入n的值:");
	scanf("%d", &n);
	
	ret = 1;
	for (i = 1; i <= n; i++) {

		ret = ret * i;
	}
	printf("n!= %d",ret);
	
	return 0;
}

【算法】求n!,求1!+2!+...+(n-1)!+n!_阶乘之和

2、求阶乘之和 n!+(n-1)!+...+1!

int main() {

	int i, j, n, ret, sum;

	printf("输入的n是:");
	scanf("%d", &n);

	sum = 0;
	for (j = 1; j <= n; j++) {

		ret = 1;
		for (i = 1; i <= j; i++) {

			ret = ret * i;
		}
		sum = sum + ret;
	}

	printf("n!= %d\n", ret);
	printf("n!+(n-1)!+...+1!= %d\n", sum);

	return 0;
}

性能优化后代码,

int main() {

	int i, n, ret, sum;

	printf("输入的n是:");
	scanf("%d", &n);

	ret = 1;
	sum = 0;
	for (i = 1; i <= n; i++) {

		ret = ret * i;
		sum = sum + ret;
	}

	printf("n!= %d\n", ret);
	printf("n!+(n-1)!+...+1!= %d\n", sum);

	return 0;
}

输出结果:

【算法】求n!,求1!+2!+...+(n-1)!+n!_n!_02


上一篇:9.1 C++ STL 排序、算数与集合
下一篇:没有了
网友评论