大數階乘的位元和精確值計算【轉】

來源:互聯網
上載者:User

標籤:

來源:http://www.cnblogs.com/stonehat/p/3603267.html

在此,頂禮膜拜一下原文作者呵呵

 

我們知道整數n的位元的計算方法為:log10(n)+1
故n!的位元為log10(n!)+1
如果要求出n!的具體值,對很大的n(例如n=1000000)來說,計算會很慢,如果僅僅是求階乘的位元,可以用斯特林(Stirling)公式求解

 

斯特林(Stirling)公式:

於是求n!的位元就是求log10((2*PI*n)^1/2*(n/e)^n)+1
即  1/2*log10(2*PI*n)+n*log10(n/e)+1
所以採用下面代碼計算階乘位元,會非常快
1 #define PI 3.1415926542 #define E 2.718281828463 int l(int n)4 {5     int s=1;6     if(n>3)7         s=log10(2*PI*n)/2+n*log10(n/E)+1;8     return s;9 }

如果要計算階乘的精確值,則可以採用下面代碼。

 1 /* 2 函數功能:計算並輸出n 的階乘 3 傳回值:階乘結果的位元 4 注意:      5      本程式直接輸出n!的結果,需要返回結果請保留long a[] 6      需要 math.h 7 */ 8  9 int factorial(int n)10 {11     long a[10000];12     int i,j,l,c,m=0,w; 13     a[0]=1; 14     for(i=1;i<=n;i++)15     { 16         c=0; 17         for(j=0;j<=m;j++)18         { 19             a[j]=a[j]*i+c; 20             c=a[j]/10000; 21             a[j]=a[j]%10000; 22         } 23         if(c>0) {m++;a[m]=c;} 24     } 25 26     w=m*4+log10(a[m])+1;27     printf("\n%ld",a[m]); 28     for(i=m-1;i>=0;i--) printf("%4.4ld",a[i]);29     return w;30 }

 

大數階乘的位元和精確值計算【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.