题意:求斐波那契序列的第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;
}