【华为练习题】大数阶乘
题目
计算阶乘n!是一件可怕的事情,因为当n并不是很大时,n!将是一个很大的值。例如13! = 6227020800,已经超过了我们常用的unsigned int类型的取值范围。请设计一个程序,使其可以计算100以内的数的阶乘,结果用字符串的形式输出
解答
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string multiple(string const &s, int n){
string result;
int overFlow = 0;
for (auto begin = s.rbegin(); begin != s.rend(); ++begin)
{
int value = (*begin - '0') * n + overFlow;
result.push_back((value % 10) + '0');
overFlow = value / 10;
}
while (overFlow)
{
result.push_back(overFlow % 10 + '0');
overFlow /= 10;
}
reverse(result.begin(),result.end());
return result;
}
string compute(int n){
static vector<string> elems;
int length = elems.size();
if (n > length)
{
for (int i = length; i < n; i++)
{
if (i == 0)
{
elems.push_back("1");
continue;
}
elems.push_back(multiple(elems[i-1], i+1));
}
}
return elems[n-1];
}
int main(){
int n;
while (cin >> n)
{
cout << compute(n) << endl;
}
return 0;
}