c中带有字符串的大数的阶乘

新手上路,请多包涵

我正在用字符串做一个阶乘程序,因为我需要大于 250 的数字的阶乘

我打算:

 string factorial(int n){
    string fact="1";
    for(int i=2; i<=n; i++){
        b=atoi(fact)*n;

    }

}

但问题是 atoi 不起作用。如何将我的字符串转换为整数。

最重要的是我想知道这种方式的程序是否可以使用例如 400 的阶乘?

原文由 Code Geas Coder 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 249
1 个回答

不知道你为什么要尝试使用字符串。可能通过不使用整数向量来节省一些空间?这是我使用整数向量存储阶乘和打印的解决方案。适用于 400 或任何大数!

 //Factorial of a big number

#include<iostream>
#include<vector>
using namespace std;

int main(){
    int num;
    cout<<"Enter the number :";
    cin>>num;
    vector<int> res;
    res.push_back(1);
    int carry=0;
    for(int i=2;i<=num;i++){
        for(int j=0;j<res.size();j++){
            int tmp=res[j]*i;
            res[j]=(tmp+carry)%10 ;
            carry=(tmp+carry)/10;

        }
        while(carry!=0){
            res.push_back(carry%10);
            carry=carry/10;
        }

    }

    for(int i=res.size()-1;i>=0;i--) cout<<res[i];
    cout<<endl;

    return 0;
}

输入数字:400 400 的阶乘:

原文由 Red John 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题