fibonacci 数列实现 log(n) and O(n)
2013-07-10 22:52
183 查看
#include <iostream> #include <vector> using namespace std; template <typename _type> class fibonacci { private : //vecotr<_type> m_mat; int m_num; public : fibonacci (_type n) : m_num(n){ } ~fibonacci () {} _type fn () ; vector<_type> fibo (const vector<_type>& mat, _type n); if (n < 0 ) return false; this->m_num = n; return true; } vector <_type> multiMat (const vector<_type>& lhsMat, const vector<_type>& rhsMat ) { /* * |a b| |e f| * |c d| |g h| * */ vector<_type> ansMat(4,0); _type ae = lhsMat[0]*rhsMat[0]; _type bg = lhsMat[1]*rhsMat[2]; _type af = lhsMat[0]*rhsMat[1]; _type bh = lhsMat[1]*rhsMat[3]; _type ce = lhsMat[2]*rhsMat[0]; _type dg = lhsMat[3]*rhsMat[2]; _type cf = lhsMat[2]*rhsMat[1]; _type dh = lhsMat[3]*rhsMat[3]; ansMat.at(0) = ae + bg; ansMat.at(1) = af + bh; ansMat.at(2) = ce + dg; ansMat.at(3) = cf + dh; return ansMat; } _type orgFn () ; }; template <typename _type > vector<_type> fibonacci<_type>::fibo (const vector<_type>& mat, _type n) { if (n < 2) return static_cast<vector<_type> > (mat); return (n % 2 == 0 ? multiMat(fibo(mat, n>>1), fibo(mat, n>>1)) : multiMat(mat, multiMat(fibo(mat, (n-1)>>1), fibo(mat, (n-1)>>1)))); } template <typename _type> _type fibonacci<_type>::fn() { if (this->m_num == 0 ) return 0; else if (this->m_num == 1) { return 1; } vector<int> orgMat; orgMat.push_back(1); orgMat.push_back(1); orgMat.push_back(1); orgMat.push_back(0); // 1 1 // 1 0 _type n = this->m_num - 1; orgMat = fibo(orgMat, n); return orgMat.at(0); } template <typename _type> _type fibonacci<_type>::orgFn (){ if (this->m_num == 0) return 0; if (this->m_num == 1) { return 1; } _type a = 0; _type b = 1; _type fn = a + b; for (int i = 1; i < this->m_num; ++i ) { fn = a + b; a = b; b = fn; } return fn; } int main (void) { fibonacci<int> fn (0); for (int i = 0; i < 40; ++i ) { fn.setN(i); cout << "n -> " << i << "\tfn : " << fn.fn() << "\torgFn : " << fn.orgFn () << endl; } return 0; }
相关文章推荐
- Fibonacci(斐波那契)数列实现
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- mips汇编语言实现Fibonacci(斐波那契)数列
- Fibonacci斐波那契数列-实现2
- 栈的应用一--斐波那契(Fibonacci)数列的实现(代码)
- python实现经典算法(2):Fibonacci(斐波那契)数列
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- 剑指offer-9-Python实现斐波那契(Fibonacci)数列
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- 斐波那契数列(fibonacci)两种python实现的效率对比
- Fibonacci 0,1,1,2,3,5,8…… 数列的实现
- 斐波那契(Fibonacci)数列的七种实现方法
- 斐波那契(Fibonacci)数列的递归和非递归实现
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- 多种方法实现Fibonacci(斐波那契)数列的生成
- Fibonacci(斐波那契)数列的递归与非递归实现 python
- 滚动数组实现斐波那契数列...
- C实现打印log到文件中的通用方面
- JNI 实现LOG打印功能
- 一种简便实用的自定义LOG实现(iOS)