Fibonacci 数求法

没有完全实现

其中代码 来源 《编程之美》2.9、《数据结构(c++语言版)》第三版


#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}
int Fib1(int n){
    if(n<=1)
        return n;
    return Fib1(n-1)+Fib1(n-2);
}

int Fib2(int n){
    //通项公式
}

int Fib3(int n,int &prev){//Time Complexity O(n);Space Complexity O(n)
    if(0==n){
        prev=1;return 0;
    }
    int prevPrev;
    prev=fib(n-1,prevPrev);
    return prev+prevPrev;
}
int Fib4(int n){//Time Complexity:O(n)
    int f=0,g=1;
    while(n--){
        g=f+g;f=g-f;
    }
    return f;
}
#ifndef MAX_N
#define MAX_N 1010;
#endif // MAX_N
#ifndef MAX_M
#define MAX_M 1010;
#endif // MAX_M

struct Matrix{
    int n,m;
    int a[MAXN][MAXM];
    void _clear(){
    n=m=0;
    memset(a,0,sizeof(a));
    }
    Matrix operator +(const Matrix &b) const{
        Matrix tmp;
        tmp.n=n;tmp.m=m;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                tmp.a[i][j]=a[i][j]+b.a[i][j];
        return tmp;
    }
    Matrix operator -(const Matrix &b) const{
        Matrix tmp;
        tmp.n=n;tmp.m=m;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                tmp.a[i][j]=a[i][j]-b.a[i][j];
        return tmp;
    }
    Matrix operator *(const Matrix &b) const{
        Matrix tmp;
        tmp._clear();
        tmp.n=n;tmp.m=b.m;
        for(int i=0;i<tmp.n;i++)
            for(int j=0;j<tmp.m;j++)
                for(int k=0;k<m;k++)
                tmp.a[i][j]+=a[i][k]*b.a[k][j];
        return tmp;
    }
};
Matrix MatrixPow(const Matrix &m,int n){
    Matrix res=Matrix::Identity;  //单位矩阵   未实现
    Matrix tmp=m;
    while(n){
        if(n&1)
            result *=tmp;
        tmp*=tmp;
    }
    return res;
}
int Fib5(int n){        //time complexity:O(log n)
    Matrix an=MatrixPow(A,n-1);//A={{1,1},{1,0}}
    return F1*an(0,0)+F0*an(1,0);
}
//扩展题
// A 为    1 1 0
//***** 1 0 1
//***** 1 0 0
long long A(long long n){
    long long f=0,g=1,h=2;
    while(n--){
        h=f+g+h;
        g=h-(g+f);
        f=h-(g+f);
    }
    return f;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值