您的位置:首页 > 其它

矩阵乘法+快速幂求斐波那契

2015-10-29 21:13 344 查看
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int n,m;
int a[2][2]={1,1,1,0};
int b[2][2]={1,0,0,1};
void jzcf(int a[2][2],int b[2][2])
{
int i,j,k;
int c[2][2];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{
c[i][j]=(c[i][j]+a[i][k]*b[k][j]);
}
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
b[i][j]=c[i][j];
}
}
}
void ksm(int n)
{
if(n==0)
{
cout<<0<<endl;
}
else
{
n--;
while(n)
{
if(n%2==1)
{
jzcf(a,b);
}
jzcf(a,a);
n/=2;
}
cout<<b[0][0]<<endl;
}
}
int main()
{

while(cin>>n)
{
ksm(n);
a[0][0]=a[0][1]=a[1][0]=b[0][0]=b[1][1]=1;
a[1][1]=b[0][1]=b[1][0]=0;

}
return 0;
}


大神博客:

母函数http://blog.csdn.net/xuzengqiang/article/details/7464337
http://www.cnblogs.com/dongsheng/archive/2013/06/02/3114073.html
原理:

f(n+1) 0 1 1 f(n) 0 1 1 1 1 f(n-1) 0 1 1 f(1) 0

= * = * * = * ' ' '*

f(n) 0 1 0 f(n-1) 0 1 0 1 0 f(n-1) 0 1 0 f(0) 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: