• 数论(fabonacci数列) hdu1568Fibonacci


    题目链接:

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

    题目意思:

    给一个i,让你求出第i个febonacci数的前四位,不足四位的直接输出。

    解题思路:

    由feibonacci数列的通项公式an=1/√5*(((1+√5)/2)^n+((√5-1)/2)^n)

    当n比较大的时候可以舍掉(√5-1)/2)^n 因为越来越小,不到一,可以舍去

    log10(an)=log10(1/√5)+n*log10((1+√5)/2) =p;

    令p=p1+p2(其中p1为p的整数部分,p2为p的小数部分),则10^(p1+p2)=10^p1*10^p2=an 其中把10^p1为an的尾部的零,去掉后不影响高位的计算。

    详细处理见代码。

    代码:

    #include<iostream>
    #include<cmath>
    #include<cstdio>
    #include<cstdlib>
    #include<string>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<stack>
    #include<list>
    #include<queue>
    #define eps 1e-6
    #define INF (1<<30)
    #define PI acos(-1.0)
    using namespace std;
    #define ba sqrt(5.0)
    
    /*
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    */
    
    //fabonacci 通项公式an=1/√5*(((1+√5)/2)^n+((√5-1)/2)^n)
    //当n比较大的时候可以舍掉(√5-1)/2)^n 因为越来越小,不到一
    
    int save[30];
    int main()
    {
        save[0]=0;
        save[1]=1;
        for(int i=2;i<20;i++)
        {
            save[i]=save[i-1]+save[i-2];
           // printf("%d\n",save[i]);
        } //前二十位都是小于5位的,直接算出来就行了
        int n;
    
        while(scanf("%d",&n)!=EOF)
        {
            if(n<20)
            {
                printf("%d\n",save[n]);
                continue;
            }
            double temp=log10(1.0/ba)+n*log10((ba+1.0)/2.0); //以十为底求出对数
    
            temp-=floor(temp);//除掉整数部分,也就是save[n]的尾部的零
            temp=pow(10.0,temp); //算出高位非零的部分
    
            while(temp<1000) //不足四位补零凑齐四位
                temp*=10;
            while(temp>=10000) //超过五位的除掉低位
                temp/=10;
            printf("%d\n",(int)temp);
    
        }
    
        return 0;
    }
    
    
    
    
    
    
    
    
    


     

  • 相关阅读:
    c++Primer再学习(1)
    c++Primer再学习练习Todo
    感悟(一)
    新目标《C++程序设计原理与实践》
    C++Primer再学习(4)
    开篇
    C++Primer再学习(3)
    C++实现的单例模式的解惑
    使用springboot缓存图片
    springboot h2 database
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2999569.html
Copyright © 2020-2023  润新知