数论 --- 斐波纳挈数列公式的变形

 

Fibonacci#

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3515    Accepted Submission(s): 1601


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
 

 

Source
  

 

Mean: 

略 

analyse:

 这题需要用到fibonacci数列的公式:F(n)=(1/√5)*{[(1+√5)/2]^n - [(1-√5)/2]^n}

在这个公式中后半部分: - [(1-√5)/2]^n 的误差在0~1之间,但对于n比较大时,他的误差就越小,所以一般情况可以忽略;

公式就变为了:F(n)=(1/√5)*[(1+√5)/2]^n] ;

这题要我们输出前四位,直接用公式是肯定会超的,所以要变形:

由于m^n=10^(n*log10(m));
先将n*log10(m)算出来,取其小数部分,再10的乘方,得整数部分为最m^n第一位数,继续乘10直到为4为数为止

 

Time complexity:O(n)

 

Source code:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//Memory   Time
// 1347K   0MS
// by : Snarl_jsb
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<climits>
#include<cmath>
#define MAX 1100
#define LL long long
using namespace std;
 
int main()
{
//    freopen("C:\\Users\\ASUS\\Desktop\\cin.txt","r",stdin);
//    freopen("C:\\Users\\ASUS\\Desktop\\cout.txt","w",stdout);
    int a[25];
    a[0]=0,a[1]=1;
    for(int i=2;i<=21;i++)
        a[i]=a[i-1]+a[i-2];
    int n;
    while(~scanf("%d",&n))
    {
        if(n<=20)
        {
            printf("%d\n",a[n]);
            continue;
        }
       double x=sqrt(5*1.0); double y=log10(1/x);
       double z=n*log10(((x+1)/2));double p=y+z;
       double q=p-(int)p;double xx=pow(double(10),q);
       for(int i=1;;++i)
       {
         xx*=10;
         if(xx>10000)
             break;
       }
       printf("%d\n",((int)xx)/10);
    }
 
    return 0;
}

 

  

 

posted @   北岛知寒  阅读(224)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示
主题色彩