fibonacci数列递归实现

  • 内容
  • 评论
  • 相关
fibonacciSequence($n-1)+$this->fibonacciSequence($n-2)."\n";
    }
}
$test = new \com\gaoxueping\test();
//echo $test->test('ct78');
for($i = 1; $i &lt; 10; $i++){ echo $test-&gt;fibonacciSequence($i)."<br />
<p>
	";
}

Java实现,有多种实现,递归,递推等等

package com.alibaba;

/**
 * Created by think.
 * Date: 15/11/2018
 * Time: 11:13
 */
public class FbTest {
    public static void main(String[] atrgs) {
//        System.out.println(fibonacci(9));
        System.out.println(fibonacciP(9));

    }

    public static int fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }

        return fibonacci(n - 1) + fibonacci(n -2);
    }

    public static int fibonacciP(int n) {
        int[] f = new int[n + 2];
        f[0] = 0;
        f[1] = 1;

        for (int i = 2; i <= n; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }

        return f[n];
    }
}

python实现

def fibonacci(n):
    if (n == 0):
        return 0;
    if (n == 1):
        return 1;
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(9))

def fibonacci(m):
    n, a, b = 0, 0, 1
    while ( n < m):
        a, b = b, a + b
        n = n + 1

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注