阶乘,大数问题

来源:互联网 发布:新版淘宝联盟返利教程 编辑:程序博客网 时间:2024/05/21 09:56
#include <iostream>#include <cmath>using namespace std;const int Maxsize=100000;//结果的最大长度int result[Maxsize],n,resultLength,*tempResult,tempResultLength;void stand(){//每次运算后对结果进行标准化,即满十进1int i;for(i=1;i<tempResultLength-2;i++){if(tempResult[i]>9){tempResult[i+1]+=tempResult[i]/10;tempResult[i]%=10;}}}int getResultLength(){//得到结果长度int i;for(i=n*n-1;i>=0;i--){if(result[i]!=0)break;}return i+1;}int getValueLength(int a){int i=0;while(a){a/=10;i++;}return i;}void copyResult(){//复制最后的结果int i;for(i=0;i<=tempResultLength;i++){result[i]=tempResult[i];}}void fun(){//大数乘法主要函数int i,j,k;for(k=1;k<=n;k++){//数值int tempK=k,valueLength=getValueLength(k);tempResultLength=Maxsize;//临时数组的最大长度tempResult=new int[tempResultLength];for(j=0;j<tempResultLength;j++)tempResult[j]=0;//清零for(j=1;j<=valueLength;j++){int tempELem=tempK%10;for(i=1;i<=resultLength;i++){//结果的每一位int tempData=result[i]*tempELem;tempResult[i+j-1]+=tempData;stand();}tempK/=10;}copyResult();resultLength=getResultLength();delete []tempResult;}}int main(){int i;cin>>n;if(n==0||n==1){cout<<1<<endl;return 0;}for(i=0;i<MaxSize;i++)result[i]=0;resultLength=1;result[1]=1;fun();for(i=resultLength;i>=0;i--)if(result[i]!=0)break;cout<<n<<"!=";for(;i>=1;i--)cout<<result[i];cout<<endl;return 0;}



写完之后才发现搞复杂了,其实可以从小到大开始乘,直到long long的最大范围,后面也这样处理,最后得到m个数(m<n),最后再进行大数处理,这个思路比我写的肯定运行的快,以后有时间再琢磨琢磨吧。

----2014-2-22 15:39

0 0
原创粉丝点击