现在的位置: 首页 > 综合 > 正文

hdu1568-Fibonacci

2013年07月13日 ⁄ 综合 ⁄ 共 1189字 ⁄ 字号 评论关闭

http://acm.hdu.edu.cn/showproblem.php?pid=1568

用到了斐波那契数列的通项公式。

先看对数的性质,loga(b^c)=c*loga(b),loga(b*c)=loga(b)+loga(c);
假设给出一个数10234432,那么log10(10234432)=log10(1.0234432*10^7)=log10(1.0234432)+7;

log10(1.0234432)就是log10(10234432)的小数部分.

log10(1.0234432)=0.010063744
10^0.010063744=1.023443198
那么要取几位就很明显了吧~
先取对数(对10取),然后得到结果的小数部分bit,pow(10.0,bit)以后如果答案还是<1000那么就一直乘10。
注意偶先处理了0~20项是为了方便处理~

这题要利用到数列的公式:an=(1/√5) * [((1+√5)/2)^n-((1-√5)/2)^n](n=1,2,3.....)

取完对数

log10(an)=-0.5*log10(5.0)+((double)n)*log(f)/log(10.0)+log10(1-((1-√5)/(1+√5))^n)其中f=(sqrt(5.0)+1.0)/2.0;
log10(1-((1-√5)/(1+√5))^n)->0
所以可以写成log10(an)=-0.5*log10(5.0)+((double)n)*log(f)/log(10.0);
最后取其小数部分。

还用到了floor函数;

[1]floor(x),有时候也写做Floor(x),其功能是“向下取整”,或者说“向下舍入”,即取不大于x的最大整数(与“四舍五入”不同,下取整是直接去掉小数部分),例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

int fi[ 25 ] = { 0 , 1 , 1 } ;

int main()
{
	int n ;
	for( int i = 3 ; i <= 25 ; ++i )
		fi[ i ] = fi[ i - 1] + fi[ i - 2 ] ;
	while( cin >> n ) 
	{
		if( n < 21 )
		{
			cout << fi[ n ] << endl ;
			continue ;
		}
		else
		{
			double temp = -0.5 * log(5.0) / log( 10.0 )+ ((double )n ) * log((sqrt(5.0) + 1.0 ) /2.0 )/log(10.0) ;
			temp -= floor( temp ) ;
			temp = pow( 10.0 , temp ) ;
			while( temp < 1000 )
				temp *= 10 ;
			temp = (int)temp ;
			cout << temp << endl ;
		}
	}
	return 0 ;
}
		

 

抱歉!评论已关闭.