hdu 3117(矩阵快速幂)

题意:求斐波那契序列的第n个数。如果超过8位,只输出前4位和后4位。
题解:后4位比较好办,直接mod10000就可以了,前4位不知道怎么求,网上看到一个人写的很详细易懂,需要用到斐波那契通项公式,详细见→传送门

#include <stdio.h>
#include <math.h>
#include <string.h>
struct Mat {
    long long g[2][2];
}ori, res;
long long n;

Mat multiply(Mat x, Mat y, int mod) {
    Mat temp;
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++) {
            temp.g[i][j] = 0;
            for (int k = 0; k < 2; k++)
                temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % mod;
        }
    return temp;
}

void calc(long long n, int mod) {
    while (n) {
        if (n & 1)
            ori = multiply(ori, res, mod);
        n >>= 1;
        res = multiply(res, res, mod);
    }
}

int main() {
    while (scanf("%lld", &n) == 1) {
        if (n == 0 || n == 1) {
            printf("%lld\n", n);
            continue;
        }
        ori.g[0][0] = 1;
        ori.g[0][1] = ori.g[1][0] = ori.g[1][1] = 0;
        res.g[0][0] = res.g[0][1] = res.g[1][0] = 1;
        res.g[1][1] = 0;
        if (n < 40) {
            calc(n - 1, 1e9);
            printf("%lld\n", ori.g[0][0]);
        }
        else {
            calc(n - 1, 10000);
            double nn = n * log10((1.0 + sqrt(5.0)) / 2.0) - 0.5 * log10(5.0);
            double temp = nn - floor(nn);
            double temp2 = pow(10, temp);
            while (temp2 < 1e3)
                temp2 *= 10;
            printf("%d...%04lld\n", (int)temp2, ori.g[0][0]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值