方法一:
矩阵(matrix)定义
一个m*n的矩阵是一个由m行n列元素排成的矩形阵列。矩阵里的元素可以是数字符号或者数学式.
形如
形如
的有序对称为 列向量Column vector
设
则
称为二阶矩阵A与平面向量X的乘积,记为AX=Y
斐波那契(Fibonacci)数列
从第三项开始,每一项都是前两项之和。
Fn
=
Fn
−
1
+
Fn
−
2
,
n⩾3
把斐波那契数列中 相邻的两项
Fn
和
Fn
−
1
写成一个2
×
1的矩阵。
F0=0
F1=1
求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、用个结构体看似没必要,但是目的是为了能够直接传矩阵数组。这是个必须记住的核心内容。