poj 1423 Big Number

來源:互聯網
上載者:User

題意:給出一個數字N,求N!的結果的位元。
首先要求一個數字有多少位,可以用(int)log10(num)+1,這樣就求出num有多少位.
數N可以到10^7這麼大,直接暴力的話 肯定逾時。
考慮下面兩種方法,個人比較推薦第二種。
第一種是直接打表,避免重複計算,如果要追求速度的話,可以在程式外打表,然後匯入,在程式中直接查,即可,那樣肯定0MS,下面的代碼是在程式中打表的,所以時間愛你耗費較多。
第二種是利用Stirling公式. n!≈sqrt(2*pi*n)*[(n/e)^n]
n越大精確度越高,這裡只要計算位元,所以是可以用的。
下面是兩個演算法的代碼

#include<stdio.h>  #include<math.h>    int num[10000001];  main()  {      int n,i,t;      double d;          for(i=1,d=0;i<10000001;i++)          {                  d+=log10(i);                  num[i]=(int)d+1;          }      for(scanf("%d",&t);t>0;t--)      {          scanf("%d",&n);          printf("%d\n",num[n]);      }  }  #include<iostream>  #include<cmath>  using namespace std;  const double e = 2.7182818284590452354, pi = 3.141592653589793239;  double strling_digits_num(int n)  {          return log10(2*pi*n)/2.0+n*(log10(n/e));     }    int main()  {          int t;          cin>>t;          while(t--)          {                  int n;                  cin>>n;                  double m=0;                  m=strling_digits_num(n);                  int answer=(int)m;                  answer++;                  cout<<answer<<endl;          }          return 0;  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.