• 斐波那契数列的几种实现方法


    定义

    /*递归*/ 
    #include<bits/stdc++.h>
    using namespace std;
    int f(int x){
    	if(x==0||x==1) return 1;
    	else return f(x-1)+f(x-2);
    }
    int main(){
    	int n;
    	scanf("%d",&n);
    	cout<<f(n)<<endl;
    	return 0;
    }
    
    
    /*类似于辗转相除的依次赋值*/
    // 0 1 1 2 3 5 8
    #include<bits/stdc++.h>
    using namespace std;
    int main(){
    	int n;
    	cin>>n;
    	int a = 0 , b = 1;
    	int res ;
    	if(n == 0) res = 0 ;
    	else if(n == 1) res = 1;
    	else{
    		for(int i = 2;i <= n; i++){
    			res = a + b;
    			a  = b;
    			b = res;
    		}
    	}
    	cout<<res<<endl;
    	return 0;
    }
    
    /*备忘录*/
    #include<bits/stdc++.h>
    using namespace std;
    const int N = 1100;
    int a[N];
    int f(int x){
    	if(a[x] >= 0) return a[x];//说明该值已经计算出
    	else return a[x]=f(x-1)+f(x-2);//计算并存储
    }
    int main(){
    	int n;
    	cin>>n;
    	memset(a, -1, sizeof a);
    	a[0] = 0 , a[1] = 1;
    	cout<<f(n)<<endl;
    	return 0;
    }
    

    矩阵快速幂

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <ctime>
    
    using namespace std;
    
    const int MOD = 1000000007;
    
    void mul(int a[][2], int b[][2], int c[][2])
    {
        int temp[][2] = {{0, 0}, {0, 0}};
        for (int i = 0; i < 2; i ++ )
            for (int j = 0; j < 2; j ++ )
                for (int k = 0; k < 2; k ++ )
                {
                    long long x = temp[i][j] + (long long)a[i][k] * b[k][j];
                    temp[i][j] = x % MOD;
                }
        for (int i = 0; i < 2; i ++ )
            for (int j = 0; j < 2; j ++ )
                c[i][j] = temp[i][j];
    }
    
    
    int f_final(long long n)
    {
        int x[2] = {1, 1};
    
        int a[2][2] = {{1, 1}, {1, 0}};
    
        int res[][2] = {{1, 0}, {0, 1}};
        int t[][2] = {{1, 1}, {1, 0}};
        long long k = n - 1;
        while (k)
        {
            if (k&1) mul(res, t, res);
            mul(t, t, t);
            k >>= 1;
        }
    
        int c[2] = {0, 0};
        for (int i = 0; i < 2; i ++ )
            for (int j = 0; j < 2; j ++ )
            {
                long long r = c[i] + (long long)x[j] * res[j][i];
                c[i] = r % MOD;
            }
    
        return c[0];
    }
    
    
    int main()
    {
        long long n ;
    
        cin >> n;
        cout << f_final(n) << endl;
    
        return 0;
    }
    
    作者:yxc
    来源:AcWing
    

    利用构造矩阵的方法(待补)原文链接
    还有篇博客介绍了如何构造矩阵,但是现在没找到链接
    补:斐波那契数列求和公式 : Sn = 2F(n) + F(n-1) - 1
    求解斐波那契数列的若干方法 - AcWing

  • 相关阅读:
    Node Express4.x 片段视图 partials
    SVG知识难点
    MongoDB的安装和配置成服务的三种方法和一些难点
    git的使用
    单击获取索引的两种方式
    IOTA初识
    开始写博客啦
    虚拟化技术
    可信计算概论
    负载均衡
  • 原文地址:https://www.cnblogs.com/OvOq/p/14853223.html
Copyright © 2020-2023  润新知