方法一:
矩陣(matrix)定義
一個m*n的矩陣是一個由m行n列元素排成的矩形陣列。矩陣裏的元素可以是數字符號或者數學式.
形如
形如
的有序對稱爲列向量Column vector
設
則
稱爲二階矩陣A與平面向量X的乘積,記爲AX=Y
斐波那契(Fibonacci)數列
從第三項開始,每一項都是前兩項之和。
把斐波那契數列中 相鄰的兩項
求F(n)等於求二階矩陣的n - 1次方,結果取矩陣第一行第一列的元素,或二階矩陣的n次方,結果取矩陣第二行第一列的元素。
原貼地址:http://blog.csdn.net/flyfish1986/article/details/48014523
=============================================================
方法二:
例題:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14685 | Accepted: 10341 |
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
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
代碼:
#include<string>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define mod 10000
struct mat
{
int a[2][2];
} ans,tem;
mat mul(mat x,mat y)
{
mat tt;
memset(tt.a,0,sizeof(tt.a));
for(int i=0; i<2; i++)
{
for(int k=0; k<2; k++)
{
if(x.a[i][k]==0) continue;
for(int j=0; j<2; j++)
{
tt.a[i][j]=(x.a[i][k]*y.a[k][j]%mod+tt.a[i][j])%mod;
}
}
}
return tt;
}
void fast(int n)
{
tem.a[1][0]=tem.a[0][1]=tem.a[0][0]=ans.a[1][1]=ans.a[0][0]=1;
tem.a[1][1]=ans.a[1][0]=ans.a[0][1]=0;
while(n>0)
{
if(n&1) ans=mul(ans,tem);
n>>=1;
tem=mul(tem,tem);
}
printf("%d\n",ans.a[0][1]%mod);
}
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n==-1) break;
fast(n);
}
return 0;
}//FROM CJZ
1、poj不支持萬能頭文件
2、要用到快速冪
3、用個結構體看似沒必要,但是目的是爲了能夠直接傳矩陣數組。這是個必須記住的核心內容。