Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0 9 999999999 1000000000 -1
Sample Output
0 34 626 6875
--------------------------------------
分析:1.运用矩阵快速幂
2.数值范围是10^9,用int足矣
3.矩阵相乘:矩阵A的列数必须等于矩阵B的行数,矩阵A与矩阵B才能相乘;
用A的第i行分别和B的第j列的各个元素相乘求和,求得C的第i行j列的元素,这种算法中,B的访问是按列进行访问的,代码如下:
void arymul(int a[4][5], int b[5][3], int c[4][3])
{
int i, j, k;
int temp;
for(i = 0; i < 4; i++){
for(j = 0; j < 3; j++){
temp = 0;
for(k = 0; k < 5; k++){
temp += a[i][k] * b[k][j];
}
c[i][j] = temp;
printf("%d/t", c[i][j]);
}
printf("%d/n");
}
}
4.斐波那契的矩阵形式,矩阵满足结合律,却不满足交换律。
--------------------------------------------
#include<iostream>
#include<cstdio>
using namespace std;
int mod = 10000;
struct matrix{//用结构体存储矩阵
int m[2][2];
};
struct matrix array;
struct matrix multiply(struct matrix x,struct matrix y ){//矩阵相乘
struct matrix temp;
for(int i = 0; i < 2; ++i){
for(int j = 0; j < 2; j++){
temp.m[i][j] = 0;
for(int k = 0; k < 2; k++){
temp.m[i][j] = (temp.m[i][j] + x.m[i][k] * y.m[k][j]) % mod;
}
}
}
return temp;
}
struct matrix quickpow(int n){//矩阵快速幂的方法。
n = n - 1;
struct matrix temp;
//初始temp为单位矩阵
temp.m[0][0] = 1;
temp.m[0][1] = 0;
temp.m[1][0] = 0;
temp.m[1][1] = 1;
while(n){
if(n&1){
temp = multiply(temp,array);
}
array = multiply(array,array);
n = n>>1;
}
return temp;
}
int main(){
int n;
while(scanf("%d",&n),n>=0){
array.m[0][0] = 1;
array.m[0][1] = 1;
array.m[1][0] = 1;
array.m[1][1] = 0;
if(n == 0||n == 1){
cout<<n<<endl;
continue;
}
struct matrix temp = quickpow(n);
int ans = temp.m[0][0];
if(ans > 999){
ans = ans % 10000;
}
cout<<ans<<endl;
}
return 0;
}