题解 | #阶乘#

阶乘

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;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
09-30 19:49
起名星人:蛮离谱的,直接要求转投销售
投递汇川技术等公司10个岗位
点赞 评论 收藏
分享
shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务