The Fibonacci number is, 5 ...... In such a wave of series, the third number is the sum of the first two.
The rabbit problem, the number of steps on the stairs, is a series of Fibonacci.
Fibonacci can be simply implemented using recursion:
1 def fib(n)2 # Calculate the nth Fibonacci Number3 return n if n == 0 || n == 14 return fib(n-1) + fib(n-2) 5 end
Simple and effective, but it takes a long time for N.
It can also be implemented through iteration.
1 def fib(n) 2 return n if n == 0 || n == 1 3 a, b = 0, 1 4 until n == 1 5 b = a + b 6 a = b - a 7 n -= 1 8 end 9 b10 end
Time complexity O (N) and space complexity O (1) are two variables A and B.
There is also a Matrix Method
According to the following recursive formula
It can be obtained by calculating the N power of the matrix [[], []. The time complexity of this calculation is O (logn)
1 require 'matrix '2 def fib (n) 3 MAT = matrix [1, 1], [1, 0] 4 return n if n = 0 | n = 1 5 return mat_n (MAT, n-1 ). first 6 end 7 8 def mat_n (ma1, n) # Calculate the n 9 return ma1 if n = 110 N of the matrix. even? ? Mat_n (ma1, n/2) ** 2: ma1 * mat_n (ma1, n-1) 11 end
These are methods that can be found online.
There is also an iterative method with the complexity of O (logn ).
The details are as follows:
Http://mitpress.mit.edu/sicp/chapter1/node15.html
The idea is to express two iterations as one iteration, so that N iterations can only be completed at O (logn) time.
In addition, all the above discussions are about positive numbers. What if the parameter of the Fibonacci series is negative?
From F (n + 2) = f (n + 1) + f (N), we can know that F (n) = f (n + 2) -F (n + 1), so the Fibonacci sequence of negative numbers also exists.
The recursive method can be obtained directly, and the iterative method can also be applied directly. This matrix method is a little troublesome. It is difficult to find this Matrix directly. You can first look at the sequence of negative numbers,
F (-1) = F (1)-f (0) = 1, F (-2) =-1, F (-3) = 2, F (-4) =-3, F (-5) = 5 ......
0 1 1 2 3 5 8 ......
0 1-1 2-3 5-8 ......
The rule is found. When the parameter is smaller than 0, the Fibonacci series is a positive and negative distribution, and exactly corresponds to the parameter greater than 0. Haha, isn't it a coincidence?
Therefore, you only need to consider parity when the parameter is positive.
A summary of the Fibonacci series