Data Structures Algorithms 简明教程

Fibonacci Series Using Recursion

Fibonacci Series Using Recursion

斐波那契数列通过将两个前一个数字相加来生成后续数字。斐波那契数列从两个数字开始 − F0 & F1 。F0 & F1 的初始值可以分别取 0, 1 或 1, 1。

Fibonacci series generates the subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

斐波那契数列满足以下条件:

Fibonacci series satisfies the following conditions −

Fn = Fn-1 + Fn-2

因此,一个斐波那契数列看起来可能是这样 −

Hence, a Fibonacci series can look like this −

F8 = 0 1 1 2 3 5 8 13

或者,这样 −

or, this −

F8 = 1 1 2 3 5 8 13 21

为了说明,F8 的斐波那契显示为 −

For illustration purpose, Fibonacci of F8 is displayed as −

fibonacci animation

Fibonacci Iterative Algorithm

首先,我们尝试起草斐波那契数列的迭代算法。

First we try to draft the iterative algorithm for Fibonacci series.

Procedure Fibonacci(n)
   declare f0, f1, fib, loop

   set f0 to 0
   set f1 to 1

   <b>display f0, f1</b>

   for loop ← 1 to n

      fib ← f0 + f1
      f0 ← f1
      f1 ← fib

      <b>display fib</b>
   end for

end procedure

Fibonacci Recursive Algorithm

让我们学习如何创建斐波那契数列的递归算法。递归的基本准则。

Let us learn how to create a recursive algorithm Fibonacci series. The base criteria of recursion.

START
Procedure Fibonacci(n)
   declare f0, f1, fib, loop

   set f0 to 0
   set f1 to 1

   display f0, f1

   for loop ← 1 to n

      fib ← f0 + f1
      f0 ← f1
      f1 ← fib

      display fib
   end for

END

Example

以下是不同编程语言中上述方法的实现 -

Following are the implementations of the above approach in various programming languages −