题目标题:
· 计算阶乘n!是一件可怕的事情,因为当n并不是很大时,n!将是一个很大的值。例如13! = 6227020800,已经超过了我们常用的unsigned int类型的取值范围。请设计一个程序,使其可以计算100以内的数的阶乘,结果用字符串的形式输出
详细描述:
· 接口说明
原型:
void CalcNN(int n, char *pOut)
输入参数:
int n 需要计算的阶乘数
输出参数:
char *pOut 结算结果,内存由调用者负责管理
返回值:
无
限制:
无
举例:
涉及知识点:
· 数字处理
性能要求:
· 无
#include <iostream>
#include <string>#include <vector>
using namespace std;
class BigInteger
{
public:
BigInteger( long long num = 0)
{
*this = num;
}
BigInteger operator=( long long num)
{
s.clear();
do{
s.push_back(num%BASE);
num = num/BASE;
}while( num >0 );
return *this;
}
BigInteger operator=(const string& str)
{
s.clear();
int x;
int len = (str.length() + 7)/WIDTH ;
for(int i = 0;i<len;i++)
{
int end = str.length() - i*WIDTH;
int start = max(0,end-WIDTH);
sscanf(str.substr(start,end - start).c_str(),"%d",&x);
s.push_back(x);
}
return *this;
}
BigInteger operator+(BigInteger x);
BigInteger operator *(BigInteger x);
public:
static const int BASE = 100000000;
static const int WIDTH = 8;
vector <int> s;
};
BigInteger BigInteger::operator+(BigInteger x)
{
BigInteger t;
t.s.clear();
int z = 0,c = 0;
for(int i = 0; i <s.size() || i<x.s.size() || c != 0; i++)
{
z = 0;
if( i <s.size() && i<x.s.size() ) { z = x.s[i] + this->s[i]; }
if( i <s.size() && i>=x.s.size() ) { z = this->s[i]; }
if( i >=s.size() && i < x.s.size() ) { z = x.s[i] ; }
z += c;
t.s.push_back(z%this->BASE);
c = z/this->BASE;
}
return t;
}
BigInteger BigInteger::operator *(BigInteger x) //第二个乘数小于等于8位
{
BigInteger t;
t.s.clear();
long long z = 0,c = 0;
for(int i = 0; i <s.size() || c != 0; i++)
{
z = 0;
if( i <s.size() ) { z = (long long)x.s[0] * (long long)this->s[i]; }
z += c;
t.s.push_back( z%this->BASE );
//cout<<i<<" :"<< z%this->BASE<<endl;
c = z/this->BASE;
}
return t;
}
void CalcNN(int n, char *pOut)
{
BigInteger a=1;
for( int i = n ; i>=1;i--)
{
a = a * i;
}
sprintf(pOut,"%d",a.s.back());
int len = strlen(pOut);
//char buf[10];
for(int i = a.s.size() -2 ;i >=0; i--)
{
sprintf(pOut+len,"%08d",a.s[i]);
len +=8;
//for(int j = 0;j<8;j++) cout<<buf[j]; //???
}
}
char p[10000];
int main()
{
int n = 0;
cin>>n;
CalcNN(n,p);
cout<<p<<endl;
return 0;
}