矩阵法求第n个斐波拉契数
来源:互联网 发布:kk聊天软件 编辑:程序博客网 时间:2024/05/23 14:28
方法一:
矩阵(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
=============================================================
方法二:
例题:
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、用个结构体看似没必要,但是目的是为了能够直接传矩阵数组。这是个必须记住的核心内容。
- 矩阵法求第n个斐波拉契数
- N*N矩阵
- N*N矩阵
- 螺旋输出N*N矩阵
- 打印 N*N 螺旋矩阵
- 打印N*N矩阵
- n*n字符矩阵旋转
- 输入N, 打印 N*N 矩阵
- M*N的矩阵
- 矩阵n次冥
- n阶螺旋矩阵
- n阶螺旋矩阵
- 求N阶矩阵
- N阶螺旋矩阵
- n阶蛇形矩阵
- M*N矩阵旋转
- n阶矩阵相乘
- 一种N*N矩阵的打印方法
- Redis 切片池与非切片池,连接指定库以及基本配置
- Jaccard相似度和广义Jaccard相似度
- TensorFlow学习(四):优化器Optimizer
- Python Module和Package辨析
- Linux下ffmpeg的卸载与安装
- 矩阵法求第n个斐波拉契数
- 高德地图 toolbar
- 万能的林萧说:一篇文章教会你,如何做到招聘要求中的“要有扎实的Java基础”。
- ios开发中直接选择一个联系人的电话号码和姓名
- 机器学习实战_决策树
- 1.vue.js实例:展现helloWord的方式
- MySql安装与使用图文教程5.7
- Android自定义View绘制几何图形
- 关于C的小程序-4