求前四位的时候直接用公式来求
求和四位的时候利用矩阵快速幂来求,每次对10000取余即可
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX_N = 3;
const int MOD = 10000;
int fib[40];
int N, M;
int get_f4( int n ){
double t1 = ( 1 + sqrt( 5.0 ) ) / 2;
double t2 = -0.5 * log10(5.0) + (double)n * log10( t1 );
double t3 = t2 - (int)t2;
int ans = pow( 10.0, t3 ) * 1000.0;
return ans;
}
void multipy( int a[MAX_N][MAX_N], int b[MAX_N][MAX_N], int c[MAX_N][MAX_N] ){
for( int i = 1; i <= 2; i++ ){
for( int j = 1; j <= 2; j++ ){
c[i][j] = 0;
for( int k = 1; k <= 2; k++ ){
c[i][j] = ( c[i][j] + a[i][k] * b[k][j] ) % MOD;
}
}
}
}
void get_matrix_pow( int a[MAX_N][MAX_N], int n ){
int ans[MAX_N][MAX_N] = {0};
int temp[MAX_N][MAX_N];
for( int i = 1; i <= 2; i++ ) ans[i][i] = 1;
while( n ){
if( n % 2 == 1 ){
multipy( ans, a, temp );
memcpy( ans, temp, sizeof( int ) * MAX_N * MAX_N );
}
multipy( a, a, temp );
memcpy( a, temp, sizeof( int ) * MAX_N * MAX_N );
n /= 2;
}
memcpy( a, ans, sizeof( int ) * MAX_N * MAX_N );
}
int main(){
fib[0] = 0;fib[1] = 1;
for( int i = 2; i < 40; i++ ){
fib[i] = fib[i-1] + fib[i-2];
}
while( scanf( "%d", &M ) != EOF ){
if( M < 40 ){
printf( "%d\n", fib[M] );
}else{
int ans_a = get_f4( M );
int a[MAX_N][MAX_N];
a[1][1] = 1;a[1][2] = 1;
a[2][1] = 1;a[2][2] = 0;
get_matrix_pow( a, M );
int ans_b = a[2][1];
printf( "%d...%04d\n", ans_a, ans_b );
}
}
return 0;
}