Use the Fibonacci (Fibonacci) sequence to solve ZZ

Source: Internet
Author: User

Describes the natural laws of the number of animals that breed and the change of plant bits. As a typical mathematical problem, the Fibonacci series are often used as examples in programming, data structures, algorithms, and other related disciplines.

The following is a simple analysis of the common algorithm for solving the Fibonacci series.

1. recursion. In most textbooks, we always like to take the Fibonacci series as an example to illustrate recursive algorithms. This is because we can intuitively see the progressive nature of the Fibonacci series from the third line of the definition formula. Its C ++ implementation is as follows:

unsigned long Fib(int n)            {            if (n <= 1) {            return n;            } else {            return Fib(n - 1) + Fib(n - 2);            }            }

The recursive algorithm is very consistent with the definition formula and easy to understand. However, there are a lot of repeated operations in the calculation process, and the time complexity reaches O (2 ^ N ), the memory used also increases with the increase of the function call stack. This is obviously not suitable for practical programs.

2. Table-driven recursion. The pure table-driven method is not mentioned here, because it is not worthwhile and irresponsible to enable a large part of space for a Fibonacci series with an unknown number of items in exchange for time. To eliminate a large number of repeated operations in the recursive method, we can store the computed median into a table and use it later:

#define MAX_LOG 20            static unsigned long Logs[MAX_LOG] = {0};            unsigned long Fib(int n)            {            if (n <= 1) {            return n;            } else if (n < MAX_LOG && Logs[n] != 0) {            return Logs[n];            } else {            Logs[n] = Fib(n - 1) + Fib(n - 2);            return Logs[n];            }            }

When N is less than the long value of the stored table, the time complexity is reduced to O (n) because each median value is calculated only once ). However, as N increases, to maintain the O (n) time complexity, you must increase the length of the stored table, which leads to a waste of storage space.

3. iterative method. Although the values of the first two items need to be used to evaluate the N of the Fibonacci series, they are only used as the intermediate values of the temporary computation and are not output as results, so there is no need to keep them, it can be converted into iterative solutions:

unsigned long Fib(int n)            {            int i;            unsigned long a = 0, b = 1, c;            if (n <= 1) {            return n;            } else {            for (i = 2; i <= n; i++) {            c = a + b;            a = b;            b = c;            }            return c;            }            }

The time complexity of the iteration method is O (n), and the memory used does not dynamically increase. I personally think that the Fibonacci series are more suitable as examples of iterative instead of recursive methods.

The following two mathematical algorithms are provided. Considering the conciseness of expression, we use MATLAB to implement:

4. transfer matrix method. This method is an example of a Markov process that is common in linear algebra. The Nth and n-1 terms of the Fibonacci series can be obtained through the n-1 iteration of the transfer matrix:

The Code is as follows:

function y = Fib(n)            first = [1; 0];            trans = [1 1; 1 0];            last = trans ^ (n - 1) * first;            y = last(1, 1);            end

The time complexity of this algorithm is equivalent to the time complexity of the calculation matrix multiplication. When calculating the Npower of a level 2 matrix, if it is expanded directly according to the matrix multiplication definition without special optimization, the time complexity is O (n ).

5. General expression method. The general formula of the Fibonacci series is as follows (slightly proof ):

You can use the generic formula to obtain any items of the Fibonacci series:

function y = Fib(n)            sr5 = sqrt(5);            y = uint32((((1 + sr5) / 2) ^ n - ((1 - sr5) / 2) ^ n) / sr5);            end

The time complexity of this method seems to be O (1), but we should also consider the time consumption of multiplication. When special optimization is not added, the time complexity of multiplication to implement n multiplication is O (n ). Considering the floating point computing efficiency and accuracy, this method is not as good as the transfer matrix method in Computer Implementation.

The following two implementation methods have special significance for computer implementation, but also have certain limitations (only implementation methods, not new algorithms ). Some C ++ programming skills are used to provide some reference value for other languages:

6. template metaprogramming method. Generally, we use templates in C ++, which are limited to class templates and function templates. In fact, C ++ supports template metaprogramming. Theoretically, any computation can be executed during compilation (even including selection, loop, recursion, and other structures ). The Code is as follows:

#define Fib(N) FibT<N>::Val            template<int n> struct FibT            {            enum            {            Val = FibT<n - 1>::Val + FibT<n - 2>::Val            };            };            template<> struct FibT<0>            {            enum            {            Val = 0            };            };            template<> struct FibT<1>            {            enum            {            Val = 1            };            };

We use a struct as the template carrier and an enumerated value to save the calculation result. The first template is a basic recursive process (the recursive algorithm is used to illustrate the simplicity and can be replaced by other algorithms to accelerate the compilation process ), the latter two templates are specific when n = 0 and 1. You can use the # define statement to abbreviated the template call as a function call method. The program calculates the required Fibonacci series during compilation, and embeds the result as a constant into the compiled program. The result is directly used during running, and the time complexity is actually changed to O (1 ). But the biggest limitation of this method is that it can only embed constants, and there is nothing in the program to do with the calculation of Fib (I ++. However, this is more intuitive and accurate than the values required for manual calculation and writing in the code, and it is more convenient and convenient than simply using the table-driven method "space for time.

7. function object method. This method is mainly used in the general algorithm of C ++ STL programming, and its execution behavior is different from the above other methods:

class Fib            {            public:            Fib() : a(0), b(1), n(0)            {            }            unsigned long operator()()            {            if (n <= 1) {            n++;            return n - 1;            } else {            int c;            c = a + b;            a = b;            b = c;            return c;            }            }            private:            int a, b, n;            };

The behavior of this function class object can be understood as a "Fibonacci series generator". Its Testing calls are as follows, and the program will print

void test(int i)            {            Fib fib;            do {            cout << fib() << endl;            } while (i--);            }

Function objects have similar behaviors as function pointers and can store some of their own attributes. Therefore, function objects are often used in STL Universal Algorithm Programming. However, it is not as flexible as a general method to evaluate a single Fibonacci series.

It is hoped that the readers will learn from the above algorithm analysis.

References:
1. Bruce Eckel, thinking in C ++ Volume 2: practical programming, Mechanical Industry Press, 2006
2. William J. Collins, data structures and the standard template library, Mechanical Industry Press, 2003
3. Knott's Surrey University, the home page for maid and the Golden Section, http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.