【ACM】杭电1141:Factstone Benchmark
生活随笔
收集整理的這篇文章主要介紹了
【ACM】杭电1141:Factstone Benchmark
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我覺得這道題 值得一寫,是因為它用到了取對數的方法來處理數值過大的階乘問題。這種方法應該熟練掌握。
分析:
問題實際上可以轉化成一個不等式: n ! < 2 ^ n?
即求使上述不等式成立的最大的整數n.
如果直接枚舉的話,勢必溢出。所以應該用取對數的方法來避免處理過大的數。
首先對不等式兩邊都取自然對數,得:
ln(n!) < n * ln(2)
這時候數據就被大大縮小了。
代碼 :
#include <stdio.h> #include <math.h> int Pow(int bottom,int bit) /* 用來求bottom的bit次方 */ {int i,res = 1;for(i = 1 ; i <= bit ; ++i)res *= bottom;return res; }int main(int argc, char *argv[]) {int yy;while(scanf("%d",&yy) != EOF && yy != 0){int bit = Pow(2,((yy - 1960) / 10 + 2)); /* 計算當年的位數 */double max = bit * log(2); /* 對這幾位所能表示的最大的數取自然對數 */double sum = 0;int i = 1;while(sum <= max){sum += log(i);++i;}printf("%d\n",i - 2);}return 0; }轉載于:https://www.cnblogs.com/whongfei/archive/2012/11/05/5247022.html
總結
以上是生活随笔為你收集整理的【ACM】杭电1141:Factstone Benchmark的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Guava 2.2-新集合类型
- 下一篇: [AWDwR4] Iteration F