1 解题思路
由于要计算第108 个fibonacii数,按照平常方法肯定溢出。
可以采取下面的方法,原理如下:
log10 123456789 = log10 1.23456789+8
log10 1.23456789 = log10 123456789 - floor(log10 123456789)
1.23456789 = 10log10 1.23456789
12.3456789 = 10×10log10 1.23456789
……
-
fabonacii公式
-
-
可将此方法用在fabonacii公式上来计算前4位。
其中最后一项经计算可知当n>20时将<10(-6),而我们需要的是前4位,所以可以将其忽略。
2 hdu2.1.1源代码
#include <iostream> #include <cmath> using namespace std; int main(int argc, char *argv[]) { int n; const double a = (-0.5)*log10(5.0); const double b = (sqrt(5.0)+1)/2; int fibo[21]={0, 1, 1}; for(int i=3; i<=20; i++) fibo[i] = fibo[i-1] + fibo[i-2]; while(cin>>n){ if(n < 20) cout<<fibo[n]<<endl; else{ double x = a +log10(b)*n; x = x - floor(x); x = pow(10.0, x); while(x < 1000) x = x * 10; cout<<(int)x<<endl; } } return 0; }
Date: 2011-08-13 00:02:42
HTML generated by org-mode 6.33x in emacs 23