基础练习 | 阶乘
花了一下午鼓捣了高精度加法函数。
一下代码中multi函数用string做容器,存在溢出的问题,可改为vector<int>或vector<long long>
#include <stdio.h> #include <memory.h> #include <math.h> #include <string> #include <vector> #include <set> #include <stack> #include <queue> #include <algorithm> #include <map> #define I scanf #define OL puts #define O printf #define F(a,b,c) for(a=b;a<c;a++) #define FF(a,b) for(a=0;a<b;a++) #define FG(a,b) for(a=b-1;a>=0;a--) #define LEN 10000 #define MAX 0x06FFFFFF #define V vector<int> using namespace std; string multi(string a,string b); int main() { // freopen("d:/input/A1130/1.txt","r",stdin); int n,i; scanf("%d",&n); string ans="1"; F(i,2,n+1){ char cnum[1000]; sprintf(cnum,"%d",i); string num(cnum); ans=multi(ans,num); } printf("%s\n",ans.c_str()); // printf("%s\n",multi("50","60").c_str()); return 0; } string multi(string a,string b){ int an=a.size(),bn=b.size(),n=an+bn,cnt=0; int i,j; FF(i,an) a[i]-=48; FF(i,bn) b[i]-=48; string ans(n,0); string* add=new string[bn]; for ( i=0 ; i<bn ; i++ ){ int t=b[bn-1-i]; add[i]=string(n,0); string &s=add[i]; for ( j=0 ; j<an ; j++ ){ s[j+i]+=a[an-1-j]*t; if(s[j+i]>9){ int d=s[j+i]/10; s[j+i]-=d*10; s[j+i+1]+=d; } } } for ( i=0 ; i<n ; i++ ){ for ( j=0 ; j<bn ; j++ ){ ans[i]+=add[j][i]; } if(ans[i]>9){ int d=ans[i]/10; ans[i]-=d*10; ans[i+1]+=d; } ans[i]+=48; } // FF(i,n) O("%d ",ans[i]-48); // OL(""); for ( i=n-1 ; i>=0 ; i-- ){ if(ans[i]!=48) break; } ans=ans.substr(0,i+1); reverse(ans.begin(),ans.end()); return ans; }