HDU1568 Fibonacci(数学)

题目链接
这道题网上题解很多.这篇博客只是为了记录一下这道题目的思想.
参考博客
考察的两个点都是以前没有接触到的.第一个是如何求前四位数.第二个是斐波那契的通项公式.第二个不再赘述,介绍一下第一个问题如何解决.
一个数字n一定能被表示成为 n = 10^A.B 而且和对数函数联系起来有一个性质
log10(n) = A.B 10^B次方恰好就是n的小数表示.所以只需要求出log10(n)然后减掉(int)log10(n)在求pow(10,k)就可以了.
代码

#define LL long long
#define pb push_back
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
#include <string>
#include <cstdio>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
using namespace std;
const int N = 10;
int f[25];
int main() {
    ios::sync_with_stdio(false);
    f[0] = 0;
    f[1] = 1;
    for (int i = 2; i <= 20; ++i) {
        f[i] = f[i - 1] + f[i - 2];
    }
    int n;
    while (cin >> n) {
        if (n <= 20) cout << f[n] << endl;
        else {
            double t1 = -log10(5) * 0.5;
            double t2 = 0.5 * (1 + sqrt(5));
            double ans = t1 + n * log10(t2);
            ans -= (LL)ans;
            ans = pow(10, ans);
            while (ans < 1000) ans *= 10;
            cout << (int)ans << endl;
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45590210/article/details/104971166