Recursive and non-recursive algorithms for Fibonacci numbers and dichotomy and their complexity analysis

Source: Internet
Author: User
Tags assert

1. What is Fibonacci number?

Here I borrowed the explanation from Baidu Encyclopedia: Fibonacci number, also known as Fibonacci series (Italian: Successione di Fibonacci), also known as the Golden section of the series, Faipot, Faipot, Sinorhizobium fredii series, refers to a series of: 0, 1, 1, 2, 3, 5, 8 , 13, 、...... In mathematics, the Fibonacci sequence is defined recursively as follows: F0=0,f1=1,fn=fn-1+fn-2 (n>=2,n∈n*), in words, the Fibonacci sequence starts with 0 and 1, and then the Fibonacci sequence coefficients are added by the previous two numbers. In particular, 0 is not the first, but the 0th.

The number in this Fibonacci sequence is called the Fibonacci number. This series is closely related to the nature plants. The number of petals in almost all flowers comes from one of the numbers in this series: the pineapple epidermal block-shaped scales are formed into two groups of opposite spirals, the number of which must be the next two digits in the series (such as left-handed 8 lines, right-handed 13 lines), and sunflower disk ... It was not until the last 1993 that a true satisfactory explanation was given to this ancient and important series: any adjacent two numbers in this series, which are divided by the same number, are the most closely proportional to 0.618034 ... This value, its limit is the so-called "Golden partition number". 2. To find the nth Fibonacci number

The nth Fibonacci number is simpler to apply directly to the formula N = 1, 2 o'clock, fib (n) = 1;n > 2 o'clock, fib (n) = fib (n-2) + fib (n-1) at the time of calculation there are two algorithms: recursive and non-recursive. As follows:

1 //non-recursive algorithm2 Long Longfib1 (size_t N) {3     Long LongA =0, B =1, C =0;4     if(N <2) {5         returnN;6     }7     Else {8          for(Long Longi =2; I <= N; ++i) {9c = A +b;TenA =b; Oneb =C; A         } -     } -         returnC; the } - intMain () - { -printf"%lld", FIB1 (Ten)); + GetChar (); -     return 0; +}//The greatest advantage of this algorithm is that there is no duplicate computation, so the efficiency is much faster than the recursive algorithm.
1 //Recursive algorithm2 Long Longfib2 (size_t N) {3     if(N <2) 4         returnN;5     returnFIB2 (N-1) + FIB2 (N-2);6 }7 intMain ()8 {9printf"%lld", Fib2 (Ten));Ten GetChar (); One     return 0; A}

Recursion can make the program look concise, but the disadvantage is that it is inefficient and can lead to stack overflow, which requires a long computation time when the number of calculations is slightly larger, and therefore requires a flexible use of recursion.

3. Two-point method to find the non-recursive algorithm of 3.1 binary lookup
1Template<typename t>2t* BinarySearch (t* array,intNumberConstt&data)3 {  4ASSERT (number>=0); 5        intleft =0; 6        intright = number-1; 7         while(Right >=Left )8        {  9               intMid = (left&right) + ((left^right) >>1); Ten               if(Array[mid] >data) One               {   Aright = mid-1;  -               }   -               Else if(Array[mid] <data) the               {   -Left = mid +1;  -               }   -               Else   +               {   -                      return(Array +mid);  +               }   A        }   at        returnNULL;  -}
3.2 Algorithm for binary lookup
1Template<typename t>2t* BinarySearch (t* left,t* right,Constt&data)3 {  4 assert (left); 5 assert (right); 6        if(Right >=Left )7        {  8t* mid =left+ (right-left)/2; 9               if(*mid = =data)Ten                      returnmid;  One               Else   A                      return*mid > data? BinarySearch (left, mid-1, data): BinarySearch (Mid +1, right, data);  -        }   -        Else   the        {   -               returnNULL;  -        }   -}
4. Complexity of time and space Complexity of Time: In general, the number of executions of basic operations in the algorithm is a function f (n) of the problem size n, which then analyzes the change of f (n) with N and determines the order of magnitude of T (N).      Here, the "O" is used to denote the order of magnitude, and the time complexity of the algorithm is given.                   T (n) =o (f (n)); It indicates that with the increase of the size of the problem, the growth rate of the algorithm's execution time is the same as the growth rate of f (n), which is called the asymptotic complexity of the algorithm and the time complexity. What we're talking about is the worst-case complexity, and the reason for this is that the worst time complexity is the upper bound of the algorithm's run time on any input instance, analyzing the worst-case scenario to estimate an upper bound of the algorithm's point-in-time. Time Complexity Analysis Method: (1) Time complexity is the function of the basic operation of the number of times, (2) The general default is the worst time complexity, that is to analyze the worst cases can be performed, (3) Ignore the constant term, (4) focus on the growth trend of the function, focus on the fastest growing expression in the functional type, ignoring coefficients; (5) The computational time complexity is an estimation of the growth trend of the execution times of the growth function with N; (6) The time complexity of the recursive algorithm is: the number of recursive which comes times * The execution of the basic operation in each recursion, the time complexity of the following seven, the time complexity of the algorithm increased: O (1) constant type log2 N) logarithmic type, O (n) linear type, O (nlog2n) Two-dimensional type, O (n^2) square, O (n^3) cubic, O (2^n) exponential type. Complexity of space:The spatial complexity of the algorithm is not to calculate the actual occupied space, but to calculate the total number of auxiliary space units of the algorithm, and the size of the problem is not related.  The spatial complexity of the algorithm s (n) is defined as the order of magnitude of space consumed by the algorithm.   S (n) =o (f (n)) if the auxiliary space required by the algorithm is a constant relative to the amount of input data n, the auxiliary space of the algorithm is called O (1); The spatial complexity of the recursive algorithm: recursive depth n the secondary space to be recursive each time, if the secondary space required for each recursion is constant, the spatial complexity of recursion is O (N). 5. Time complexity and spatial complexity analysis of Fibonacci numbersanalysis of time complexity of 5.1 non-recursive algorithm

Using a non-recursive algorithm to find the nth Fibonacci number, the first two numbers are added from the 2nd number, then the last number is assigned to the previous number, and then the first two numbers are added. And so on and so on until the nth number, with the number of n-1 and the number of n-2 to calculate the results, so the advantage is that we only calculate the n-1 times to find out the result, that is, the time complexity of O (n); We take the code test Number 10 as an example to find the tenth number of the process. When n=10, enter the function first to judge, and then go to the following branch began to calculate the calculation of N-1 times, the result is the time complexity O (N).

Spatial complexity analysis of non-recursive algorithm

Time complexity analysis of 5.2 recursive algorithm

In the recursive algorithm, solve FIB2 (n) and push it to solve Fib2 (n-1) and Fib2 (n-2). In other words, to calculate FIB2 (n), you must first calculate

FIB2 (n-1) and Fib2 (n-2), while the calculation of FIB2 (n-1) and Fib2 (N-2), in accordance with the expression and calculation of the law, the first calculation must first calculate FIB2 (n-1), and Fib2 (n-1) from FIB2 (n-2) and fib2 (n-3) calculated, and Fib2 (n-2) is calculated by FIB2 (n-3) and Fib2 (n-4) ... And so on, and so on, the surface does not see any complexity, but careful analysis shows that each branch of computing Fib2 (n) will derive the calculation until (1) and fib (0), that is, each branch has to calculate the number itself to 1 of the Fibonacci sequence, which increases the large and jumbled computation, or 10 For example, the detailed calculation of the figure represents the nth Fibonacci number, the figure does not all draw the calculation steps, but it is sufficient to explain the problem, each step of its calculation is divided into the calculation of the first two Fibonacci number, and so on. Then this formed a binary tree, although not full of two fork tree, but we analyzed the worst time complexity, and as long as the estimated recursive number of times with the trend of n growth, it can be approximated as full two fork tree, where the number of nodes is the number of calculations, that is, the complexity, by the formula: number of nodes =2^ H-1 (h is the height of the tree) can be O (2^n).

The time complexity of recursion is: recursive times * The number of times a basic operation is performed per recursive, so the time complexity is: O (2^n)

Spatial complexity analysis of recursive algorithms:

The deepest recursion takes up enough space to accommodate all of its recursive processes. Recursive generation of the stack is to be destroyed, so the space is released, to return to the previous stack to continue to calculate the number after the + number, so it needs not always accumulated space, and then the resulting stack space is less than the deepest recursion of the space consumed.

Recursive depth * The number of secondary spaces required for each recursion, so the spatial complexity is: O (N)

6. Find the time complexity of the dichotomy and the space complexity 6.1 non-recursive algorithm analysis: Assuming the worst case, after the X-time loop is found, then: 2^x=n; X=logn (if not written in the algorithm, the log default base is 2) the basic number of cycles is log2 N, so: The time complexity is O (Logn), because the secondary space is a constant level, so: space complexity is O (1); 6.2 Recursive algorithm complexity analysis assuming worst case, the loop is found after X times , then: 2^x=n; X=logn (if not written in the algorithm, the log default base is 2) the number and depth of recursion is log2 N, each time the required secondary space is a constant level: time complexity: O (log2 N), spatial complexity: O (log2n). 7. Extended-----to seek 1+2+3+...+n without cyclic method and recursive method (think of a solution with the complexity of O (1))
1 classTemp2 {3  Public:4 Temp () {5++N;6Sum + =N;7     }8     Static voidReset () {9N =0;TenSum =0; One     } A     Static intgetsum () { -         returnSum; -     } the Private: -     Static intN; -     Static intSum; - }; + intTemp::n =0; - intTemp::sum =0; + intSolution_sum (intN) { A Temp::reset (); atTemp *a =NewTemp[n]; - Delete[]a; -A =0; -     returntemp::getsum (); - } - intMain () { incout << Solution_sum ( -) <<Endl; - GetChar (); to     return 0; +  -}

Recursive and non-recursive algorithms for Fibonacci numbers and dichotomy and their complexity analysis

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.