矩阵法求第n个斐波拉契数

来源:互联网 发布:kk聊天软件 编辑:程序博客网 时间:2024/05/23 14:28

方法一:

矩阵(matrix)定义

一个m*n的矩阵是一个由m行n列元素排成的矩形阵列。矩阵里的元素可以是数字符号或者数学式.

形如

{acbd}
的数表称为二阶矩阵,它由二行二列组成,其中a,b,c,d称为这个矩阵的元素。

形如 

{x1x2}

的有序对称为列向量Column vector

A={acbd}

X={x1x2}

Y={ax1+bx2cx1+dx2}

称为二阶矩阵A与平面向量X的乘积,记为AX=Y

斐波那契(Fibonacci)数列

从第三项开始,每一项都是前两项之和。 
Fn=Fn  1 +Fn  2n3

把斐波那契数列中 相邻的两项FnFn  1写成一个2×1的矩阵。 
F0=0 
F1=1

{FnFn1}

={Fn1+Fn2Fn1}

={1×Fn1+1×Fn21×Fn1+0×Fn2}

={1110}×{Fn1Fn2}

={1110}n1×{F1F0}

={1110}n1×{10}

求F(n)等于求二阶矩阵的n - 1次方,结果取矩阵第一行第一列的元素,或二阶矩阵的n次方,结果取矩阵第二行第一列的元素。


原贴地址:http://blog.csdn.net/flyfish1986/article/details/48014523

=============================================================

方法二:



例题:

Fibonacci
Time Limit: 1000MS Memory Limit: 65536KTotal 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

099999999991000000000-1

Sample Output

0346266875

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 10000struct 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、用个结构体看似没必要,但是目的是为了能够直接传矩阵数组。这是个必须记住的核心内容。

0 0
原创粉丝点击