zoukankan      html  css  js  c++  java
  • 简单实用算法— 求斐波那契数列

    变量定义:

    • n:所求斐波那契数列数在第几项

    注:斐波那契数列指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(1)=1,F(2)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 3,n ∈ N*)。

    算法代码(推荐):

    //变量存储+循环
    public int fib(int n) {
        int first = 1;
        int second = 1;
        int third = 2;
        for (int i = 3; i <= n; i++) {
            third = first + second;
            first = second;
            second = third;
        }
        return third;
    }
    

    其它方法(仅供参考):

    //递归法(不推荐)
    public int fib(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        return fib(n - 2) + fib(n - 1);
    }
    
    //数组+循环(推荐使用,可返回斐波那契数列前n项数)
    public int fib(int n) {
        int[] fib = new int[n];
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i < n; i++) {
            fib[i] = fib[i - 2] + fib[i - 1];
        }
        return fib[n - 1];
    }
    
    //公式法-使用斐波那契数列通项公式(不推荐,多次指数运算会积累误差)
    public int fib(int n) {
         double c = Math.Sqrt(5);
         return (int) ((Math.Pow((1 + c) / 2, n) - Math.Pow((1 - c) / 2, n)) / c);
     }
    
    //尾递归法(不推荐,没有完全解决递归的性能损耗的问题)
    public int fib(int n, int first, int second) {
        if (n <= 1) {
            return first;
        } else {
            return fib(n-1,second,first+second);
        }
    }
    
    //矩阵快速幂求解斐波那契数列(仅供参考)
    //https://blog.csdn.net/computer_user/article/details/86927209
    

    相关文章:
    [算法]还在用递归实现斐波那契数列,面试官一定会鄙视你到死——博客园
    矩阵快速幂求解斐波那契系列问题——CSDN

  • 相关阅读:
    合并字符串中的多个空格
    IfcSpecularRoughness
    IfcSpecularExponent
    IfcPresentableText
    IfcFontWeight
    IfcFontVariant
    uwb ifc模型定位測試
    IfcFontStyle
    IfcGeometricModelResource
    qt6安装
  • 原文地址:https://www.cnblogs.com/timefiles/p/FindFibonacciSequence.html
Copyright © 2011-2022 走看看