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

 
描述

大家都知道阶乘这个概念,举个简单的例子: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)
 
 
posted @ 2016-01-19 11:50  sharpfeng  阅读(465)  评论(0编辑  收藏  举报