calculate Fibonacci Num by using Dynamic plan method
来源:互联网 发布:linux 直接回到根目录 编辑:程序博客网 时间:2024/06/14 11:29
/*
*filename: fibonacci.cpp
*date: 2006.10.1
*created: karl zheng
*description: MatrixMultiplication for calculate Fibonacci No. n,cost: logN
*/
#include <stdafx.h>
#include <stdio.h>
#include<iostream>
#include "string.h"
void MatrixMultiply2By2(int a[2][2],int b[2][2],int c[2][2])
{
//c[1][1]=a[1][1]*b[1][1]+a[1][2]*b[2][1]; //it's strange:out bound but no compiler error message
c[0][0]=a[0][0]*b[0][0]+a[0][1]*b[1][0];
c[0][1]=a[0][0]*b[1][0]+a[0][1]*b[1][1];
c[1][0]=a[1][0]*b[0][0]+a[1][1]*b[1][0];
c[1][1]=a[1][0]*b[0][1]+a[1][1]*b[1][1];
}
void MatrixMultiply2By2_n_times_Power(int a[2][2],int n,int c[2][2])
{
int temp[2][2];
if(1==n)
{
c[0][0]=a[0][0];
c[0][1]=a[0][1];
c[1][0]=a[1][0];
c[1][1]=a[1][1];
return;
};
if(2==n)
{
MatrixMultiply2By2(a,a,c);
return;
};
if(n%2)//n is odd
{
MatrixMultiply2By2_n_times_Power(a,n/2,temp);
MatrixMultiply2By2(temp,temp,c);
temp[0][0]=c[0][0];
temp[0][1]=c[0][1];
temp[1][0]=c[1][0];
temp[1][1]=c[1][1];
MatrixMultiply2By2(a,temp,c);
return;
}
else//n is even
{
MatrixMultiply2By2_n_times_Power(a,n/2,c);
temp[0][0]=c[0][0];
temp[0][1]=c[0][1];
temp[1][0]=c[1][0];
temp[1][1]=c[1][1];
MatrixMultiply2By2(temp,temp,c);
return;
}
}
int main(int argc,char *argv[])
{
//char t[2][3]={'a'};
int a[2][2]={{1,1},{1,0}};
int c[2][2]={{1,1},{1,0}};;
//MatrixMultiply2By2(a,a,c);
int n,n1;
using namespace std;
while(true){
cin>>n;
if(n<0)
{
cout<<" input Negative No.Error";
return 0;
};
if(0==n)
{
cout<<"Fibonacci("<<n<<")"<<a[1][1];
return 0;
};
MatrixMultiply2By2_n_times_Power(a,n,c);
cout<<"MatrixMultiplication for calculate Fibonacci No. n,cost: logN"<<endl;
cout<<"Fibonacci("<<n<<")="<<c[0][1];
//getch();
}
return 0;
}
- calculate Fibonacci Num by using Dynamic plan method
- Calculate 1 plus to 100 by Using C++
- Could not calculate build plan
- Could not calculate build plan
- Could not calculate build plan
- maven问题解决“Could not calculate build plan...”
- Perl dynamic property, method
- Runtime--Dynamic Method Resolution
- Using Dynamic Libraries(Updating)
- Using Dynamic Libraries
- maven问题之Could not calculate build plan:
- maven创建项目报Could not calculate build plan...
- Could not calculate build plan Maven设置代理
- [问题解决] maven: Could not calculate build plan: xxx
- maven 出现错误:Could not calculate build plan
- could not calculate build plan:插件版本问题
- 解决Maven的Could not calculate build plan的方法
- Maven:解决“Could not calculate build plan”问题
- Orange'S:一个操作系统的实现
- 《JAVA编程思想》第四版学习 需要我记住的something --访问控制
- 使用QTWebkit
- .NET Windows Form开发心得
- JAVA 用得比较少的关键字以及语法
- calculate Fibonacci Num by using Dynamic plan method
- ON_COMMAND ON_MESSAGE ON_NOTIFY区别与联系
- 扩展GridView之添加单选列
- web developer tips (2):样式应用工具栏的工作模式
- 高效能人士的七个习惯
- C#里的一些加密解密标准函数示例——DES,SHA1,RSA
- 简单工厂、工厂方法和抽象工厂模式
- 关于foreach的使用
- 不限位数的十进制正整数类,可进行加和乘操作