使用元编程和模板递归技术,既可以使最原始的递归方程具备惊人的快速高效。
template <int T> class metafib { public: static const long long fib=metafib<T-1>::fib+metafib<T-2>::fib; }; template <> class metafib<1> { public: static const int fib=1; }; template <> class metafib<2> { public: static const int fib=2; };
测试代码:
int main(){ long a1=clock(); cout<<metafib<200>::fib<<endl; long a2=clock(); cout<<a2-a1; }
速度与迭代法的fib近似,
跌打法fib:
long long fibcal(long long n){ if(n<=2) return n; n-=2; long long a=1; long long b=2; while(n--){ b=a+b; a=b-a; } return b; };
时间: 2024-11-07 04:44:15