hdu-1568-Fibonacci(斐波那契数列的性质)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1568

Problem Description

2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列
(f[0]=0,f[1]=1;f[i] = f[i-1]+f[i-2](i>=2))的值全部给背了下来。
接下来,CodeStar决定要考考他,于是每问他一个数字,他就要把答案说出来,不过有的数字太长了。所以规定超过4位的只要说出前4位就可以了,可是CodeStar自己又记不住。于是他决定编写一个程序来测验zouyu说的是否正确。

 

Input

输入若干数字n(0 <= n <= 100000000),每个数字一行。读到文件尾。

 

Output

输出f[n]的前4个数字(若不足4个数字,就全部输出)。

 

Sample Input

 

0 1 2 3 4 5 35 36 37 38 39 40

 

Sample Output

 

0 1 1 2 3 5 9227 1493 2415 3908 6324 1023

题目大意,中文题,很明显;

输出数列的前四位

斐波那契数列的通项:

f[n]=f[n-1]+f[n-2]

化简得:

1/\sqrt{5}*(\frac{1+\sqrt{5}}{2})^{n}*(1-(\frac{1-\sqrt{5}}{1+\sqrt{5}})^{n})

后面的那个在n较大时趋近于0

用对数函数转换一下即可

ac:

#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<bitset> 
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  

#define ll long long  
#define INF 0x3f3f3f3f  
#define mod 100000000000
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b) 
#define clean(a,b) memset(a,b,sizeof(a))// 水印 
//std::ios::sync_with_stdio(false);
ll f[1010];

void intt()
{
	f[0]=0;
	f[1]=1;
	f[2]=1;
	int k=3;
	while(f[k-1]<1e17)
	{
		f[k]=f[k-1]+f[k-2];
		//cout<<k<<" "<<f[k]<<endl;
		k++;
	}
}

int main()
{
	ll n;
	intt();
	while(cin>>n)
	{
		if(n<80)
		{
			ll ans=f[n];
			while(ans>=10000)
				ans=ans/10;
			cout<<ans<<endl;
		}
		else
		{
			//cout<<n<<" ";
			//cout<<log10(5.0)<<" "<<log10(sqrt(5.0)+1)<<endl;
			
			double ans=n*log10((sqrt(5.0)+1.0)/2)-0.5*log10(5);
			ans=ans-int(ans);
			ans=pow(10.0,ans);
			while(ans<1000)
				ans=ans*10;
			cout<<int(ans)<<endl;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/81488428