首页 > 编程语言 > 详细

19-语言入门-19-另一种阶乘问题

时间:2016-01-19 12:19:28      阅读:239      评论:0      收藏:0      [点我收藏+]
?
描述

大家都知道阶乘这个概念,举个简单的例子:5=1*2*3*4*5.现在我们引入一种新的阶乘概念,将原来的每个数相乘变为i不大于n的所有奇数相乘例如:5!!=1*3*5.现在明白现在这种阶乘的意思了吧!
现在你的任务是求出1!!+2!!......+n!!的正确值(n<=20)

输入
第一行输入一个a(a<=20),代表共有a组测试数据
接下来a行各行输入一个n.
输出
各行输出结果一个整数R表示1!!+2!!......+n!!的正确值
样例输入
2
3
5
样例输出
5
23
?
?
代码:
?
#include <stdio.h>

//计算输入的n的结果
static int calResult(int n);


int main()
{
???
int readLen = 0;
???
scanf("%d",&readLen);
???
getchar();
???
???
while (readLen > 0)
??? {
???????
int n = 0;
???????
scanf("%d",&n);
???????
getchar();
???????
???????
printf("%d\n",calResult(n));
???????
??????? --readLen;
??? }

???
return 0;
}

//计算输入的n的结果
static int calResult(int n)
{
???
//保存结果
???
int result = 0;
???
//游标所在n[i]的新阶乘的值
???
int currValue = 1;
???
//游标 [1,n]
???
int step = 1;
???
for (; step<=n; ++step)
??? {
???????
//偶数和上一个奇数的新阶乘值的结果一致
???????
if (step % 2 != 0)
??????? {
??????????? currValue = currValue*step;
??????? }
???????
??????? result += currValue;
??? }
???
???
return result;
}
?
避免了每一个n都按照新的阶乘算法进行一次计算,利用上次计算的值,作为中介,使得运算时间是O(n),
而不是O(n2)
?
?

19-语言入门-19-另一种阶乘问题

原文:http://www.cnblogs.com/sharpfeng/p/5141734.html

(1)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!