题意
求 的小数点最后三位数。
思路
可以递推求解,但注意到数据范围很大,所以先推导再加速。
令 ,又 ,所以就有 ,则 的整数部分为 。
因为 ,那么 ,则 ,其中 以及 为方程的解。
即可得出递推方程:
定义 ,那么我们只需计算矩阵 的 次幂,然后乘以向量 ,得到的第一个元素就是 。
再计算除以 的余数即可。
如果计算为负数,加上 即可。
使用矩阵快速幂进行计算,这里不多解释。
代码
#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;
}