题解 | #阶乘#

阶乘

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

#include "iostream"
using namespace std;

// qusetion:输入n, 求y1=1!+3!+...m!(m是小于等于n的最大奇数) y2=2!+4!+...p!(p是小于等于n的最大偶数)。
// analyse:
// input:4
// y1 = 1!+3! = 1 + 6 = 7
// y2 = 2!+4! = 2 + 24 =26

// maybe input is so large, therefore use string to storage the big int;

string add(string a,string b){                                      // 字符串加法
    int carry=0;
    string res;
    long long unsigned int i=0;
    for(;i<a.size()&&i<b.size();i++){
        int temp = (a[a.size()-i-1]-'0')+(b[b.size()-i-1]-'0')+carry;
        carry = temp/10;
        temp = temp%10;
        char charTemp = temp+'0';
        res = charTemp + res;
    }
    while(i<a.size()){
        int temp  = (a[a.size()-i-1]-'0')+carry;
        carry = temp/10;
        temp = temp%10;
        char charTemp = temp+'0';
        res = charTemp + res;
        i++;
    }
    while(i<b.size()){
        int temp  = (b[b.size()-i-1]-'0')+carry;
        carry = temp/10;
        temp = temp%10;
        char charTemp = temp+'0';
        res = charTemp + res;
        i++;
    }
    if(carry!=0){
        char charTemp = carry+'0';
        res = charTemp + res;
    }
    return res;
}

string mulBasic(string a,int b){
    int carry=0,power=1;
    long long unsigned int i=0;
    string res;
    for(;i<a.size();i++){
        int temp = (a[a.size()-i-1]-'0')*b+carry;
        carry = temp/10;
        temp = temp%10;
        char charTemp = temp+'0';
        res = charTemp+res;
    }
    if(carry!=0){
        char charTemp = carry+'0';
        res = charTemp + res;
    }
    return res;
}

string mul(string a,string b){
    string res="0";
    for(long long unsigned i=0;i<b.size();i++){
        string y = mulBasic(a,b[b.size()-i-1]-'0');

        for(int j=0;j<i;j++) y = y+'0';
//        cout<< y<<endl;
        res = add(res,y);
    }
    return res;
}

string intToStr(long long int input){           // 将int转为string进行字符串加法乘法
    string res = "";
    while(input){
        char temp = input%10+'0';
        res = temp +res;
        input = input/10;
    }
    return res;
}

string JieCheng(long long int input){               // 函数:阶乘计算
    string res = "1";
    for(long long int i=2;i<=input;i++){
        res = mul(res,intToStr(i));
    }
    return res;
}



int main(){
    long long int input;
    while(cin>>input){
        string resJi="0",resOu="0";
        for(long long int i=1;i<=input;i++){
            if(i%2==0) resOu=add(resOu,JieCheng(i));    // 奇数阶乘相加
            else resJi=add(resJi,JieCheng(i));          // 偶数阶乘相加
        }
        cout<<resJi<<" "<<resOu<<endl;
    }
    return 0;
}

全部评论

相关推荐

11-27 12:43
已编辑
门头沟学院 C++
点赞 评论 收藏
分享
11-05 07:29
贵州大学 Java
点赞 评论 收藏
分享
11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务