牛客網 計算機理念考研複試機試題 N的階乘
求n的階乘,n最大爲1000,long long也存不下,考的是大整數的乘法和加法,即高精度。
#include <iostream>
#include <queue>
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <string>
#include <cstdlib>
#include <stack>
#include <vector>
#include <math.h>
#include <algorithm>
#include <typeinfo>
#include <cstring>
using namespace std;
typedef long long ll;
string sum(string a,string b){
if(a.length()<b.length()){
string tmp=a;
a=b;
b=tmp;
}
int len1=a.length(),len2=b.length();
for(int i=len1-1,j=len2-1;i>=0;i--,j--){
a[i]=(j>=0)?(a[i]+b[j]-'0'):a[i];
if(a[i]>'9'){
a[i]-=10;
if(i)
a[i-1]++;
else{
a='1'+a;
}
}
}
return a;
}
string mul(string a,string b){
if(a.length()<b.length()){
string tmp=a;
a=b;
b=tmp;
}
int len1=a.length(),len2=b.length();
string res[len2];
string ans="";
for(int j=len2-1;j>=0;j--){
res[len2-1-j]=a;
int in=0;
for(int i=len1-1;i>=0;i--){
int t1=a[i]-'0',t2=b[j]-'0';
res[len2-j-1][i]=(t1*t2+in)%10+'0';
in=(t1*t2+in)/10;
//cout<<res[len2-j-1][i]<<endl;
if(!i&&in){
res[len2-j-1]=(char)(in+'0')+res[len2-j-1];
}
}
//cout<<"for"<<endl;
for(int k=j;k<len2-1;k++){
res[len2-j-1]+='0';
}
}
for(int j=0;j<len2;j++){
//cout<<res[j]<<endl;
ans=sum(ans,res[j]);
}
return ans;
}
string D2S(int n){
string ans="";
while(n){
ans+=(char)(n%10+'0');
n/=10;
}
reverse(ans.begin(),ans.end());
return ans;
}
int main(int argc, char const *argv[])
{
int n;
while(cin>>n){
string ans="1";
for(int i=2;i<=n;i++){
string t=D2S(i);
ans=mul(ans,t);
}
cout<<ans<<endl;
}
return 0;
}