题解 | #阶乘# 部分递归,部分使用vector

阶乘

https://www.nowcoder.com/practice/e58c8a55162d49c48115bdfa5da7da56

#include <iostream>
#include <vector>
using namespace std;
int jc(int a) //计算一个数的阶乘,采用递归
{
    if (a == 1) 
    {
      return a;
    }
     return (a * jc(a-1));
}
int main() {
    int a;
    while (cin >> a) 
    { // 注意 while 处理多个 case
         vector<int> ji; //存储奇数子项阶乘
         vector<int> ou; //存储偶数子项阶乘
         int temp = a;
         if(a % 2 == 0)
         {
            temp--;
          while (temp > 0) 
          {
            ji.push_back(jc(temp)); //存入奇数待求和序列
            temp -= 2;
          }
            temp = a;
            while (temp > 0) 
            {
            ou.push_back(jc(temp));//存入偶数待求和序列
            temp -= 2;
            }
         }else
         {
            while(temp > 0)
            {
                ji.push_back(jc(temp));
                temp -= 2;
            }
            temp = a;
            temp --;
            while (temp > 0) 
            {
                ou.push_back(jc(temp));
                temp -= 2;
            }
         }
         temp = 0;
         for (int i = 0; i < ji.size(); i++) 
         {
            temp += ji[i];   //求和并输出
         }
         cout << temp;
         cout << " ";
         temp = 0;
         for (int i = 0; i < ou.size(); i++) 
         {
            temp += ou[i];  //求和并输出
         }
         cout << temp;
         cout << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务