跳到正文

题解

题解:P13459 [GCJ 2008 #1A] Numbers

#SUSPENDED#约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年8月10日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 4 分钟
获赞
1
题目
P13459

版本

  1. v1当前

题意

求 (3+5)n(3+\sqrt{5})^n 的小数点最后三位数。

思路

可以递推求解,但注意到数据范围很大,所以先推导再加速。

令 an=(3+5)na_n=(3+\sqrt{5})^n,又 0≤(3−5)n≤10\le (3-\sqrt{5})^n\le 1,所以就有 (3+5)n=an−(3−5)n(3+\sqrt5)^n = a_n - (3-\sqrt5)^n,则 ana_n 的整数部分为 an−1 a_n - 1。

因为 an−3=5a_n-3=\sqrt5,那么 (an−3)2=5(a_n-3)^2=5,则 an2−6t+4=0 a_n ^2-6t+4=0,其中 3+53+\sqrt{5} 以及 3−53-\sqrt{5} 为方程的解。

即可得出递推方程:

an={2n=06n=16an−1−4an−2otherwise.a_n = \begin{cases} 2 & n=0 \\ 6 & n=1 \\ 6a_{n-1} - 4a_{n-2} & \text{otherwise.} \end{cases}

定义 M=[6−410]M = \begin{bmatrix} 6 & -4 \\ 1 & 0 \end{bmatrix},那么我们只需计算矩阵 MM 的 n−1n-1 次幂,然后乘以向量 (6,2)T(6,2)^T,得到的第一个元素就是 ana_n。

再计算除以 10001000 的余数即可。

如果计算为负数,加上 10001000 即可。

使用矩阵快速幂进行计算,这里不多解释。

代码

C++
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000;
struct Matrix {
    long long m[2][2];
};
Matrix multiply(const Matrix& a, const Matrix& b) {
    Matrix res;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            long long t = a.m[i][0] * b.m[0][j] + a.m[i][1] * b.m[1][j];
            t %= mod;
            if (t < 0) t += mod;
            res.m[i][j] = t;
        }
    }
    return res;
}
Matrix power_matrix(Matrix base, long long exp) {
    Matrix res;
    res.m[0][0] = 1; res.m[0][1] = 0;
    res.m[1][0] = 0; res.m[1][1] = 1;
    while (exp) {
        if (exp & 1) 
            res = multiply(res, base);
        base = multiply(base, base);
        exp >>= 1;
    }
    return res;
}
int main() {
    int T;
    scanf("%d", &T);
    for (int t = 1; t <= T; t++) {
        long long n;
        scanf("%lld", &n);
        Matrix M;
        M.m[0][0] = 6; M.m[0][1] = -4;M.m[1][0] = 1; M.m[1][1] = 0;
        Matrix M_exp = power_matrix(M, n-1);
        long long x = (M_exp.m[0][0] * 6 + M_exp.m[0][1] * 2) % mod;
        if (x < 0) x += mod;
        long long result = (x - 1) % mod;
        if (result < 0) result += mod;
        printf("Case #%d: %03lld\n", t, result);
    }
    return 0;
}
原文