int - 2147483648~2147483647
long long:-9223372036854775808~9223372036854775807
unsigned int 0~4294967295
unsigned long 0~4294967295
unsigned long long:0~1844674407370955161
而20!(2,432,902,008,176,640,000)就已超過了unsigned long long的上限,10000的階乘結果為35660位,因此常規的類型變數無法儲存我們想要得到的大數階乘值的,那怎麼解決呢?
用數組! int result[int]足矣。別的不多講了,上代碼
/*<br />author:m_nValue<br />time:28/03/2011<br />email:shiweimin1828@163.com<br />*/<br />#include <iostream><br />#include <math.h><br />#include <fstream><br />#define N 10000 //10000!<br />using namespace std;<br />int *Multi(int *num1, int& size1, int *num2, int size2);<br />bool NextNum2(int *num2,int size2);<br />int main()<br />{<br />int num1[5]={1,0,0,0,0};//N<br />int num2[5]={0,9,9,9,9};//N-1<br />int size1=5;//num1的初始大小<br />int *bufR;<br />bufR=Multi(num1,size1,num2,5);<br />for(int i=1;i<N-1;i++)<br />{<br />if(!NextNum2(num2,5))<br />break;<br />bufR=Multi(bufR,size1,num2,5);<br />}<br />fstream ifs("result.txt",ios::out);//結果匯出到文字檔<br />for(int i=0;i<size1;i++)<br />{<br />cout<<bufR[i];<br />ifs<<bufR[i];<br />}<br />ifs.close();<br />cout<<endl<<endl<<"總共:"<<size1<<endl;<br />system("pause");<br />return 0;<br />}<br />int *Multi(int *num1, int& size1, int *num2, int size2)<br />{<br />int size=size1+size2;<br />int *pResult=new int[size];<br />memset(pResult,0,size*sizeof(int));<br />int count=-1,k,i=0,j=0;<br />for(i=size2-1;i>=0;i--)<br />{<br />count++;<br />k=count;<br />for(j=size1-1;j>=0;j--)<br />pResult[k++]+=num2[i]*num1[j];<br />}<br />for(i=0;i<size;i++)<br />{<br />if(pResult[i]>=10)<br />{<br />pResult[i+1]+=pResult[i]/10;<br />pResult[i]%=10;<br />}<br />}<br />j=0;<br />for(i=size-1;i>=0;i--)<br />{<br />if(pResult[i]==0)<br />continue;<br />else<br />{<br />size1=i+1;<br />break;<br />}<br />}<br />int *temp=new int[size1];<br />for(i=size1-1;i>=0;i--)<br />temp[j++]=pResult[i];<br />delete []pResult;<br />return temp;<br />}<br />bool NextNum2(int *num2,int size2)<br />{<br />int nextNum=0;<br />for(int i=0;i<size2;i++)<br />{<br />nextNum+=num2[i]*(int)pow(10.0,(size2-i-1));<br />}<br />if(nextNum<=1)<br />return false;<br />nextNum-=1;<br />for(int i=0;i<size2;i++)<br />{<br />num2[i]=nextNum/(int)pow(10.0,size2-i-1);<br />nextNum%=(int)pow(10.0,size2-i-1);<br />}<br />return true;<br />}