The beauty of programming: 2.9 Fibonacci series, 2.9 Fibonacci

Source: Internet
Author: User

The beauty of programming: 2.9 Fibonacci series, 2.9 Fibonacci

The Fibonacci series is a classic example of recursion when we are learning the C language. Of course, there will also be an example of the tower of legends.

This problem is defined as follows:

0 (x <= 0)

F (x) = 1 (x = 1)

F (x-1) + f (x-2) (x> 1)

After seeing this recursive formula, we can easily write the following code:

Function declaration:

typedef long long ll;

ll DutFibonacci_1(int);

Function Definition:

/* Recursive solution of the classic Fibonacci series, and everyone knows that this method is very inefficient */ll DutFibonacci_1 (int n) {if (n <= 0) return 0; else if (n = 1) return 1; elsereturn DutFibonacci_1 (n-1) + DutFibonacci_1 (n-2 );}

However, when you enter a large x value, you will find that you have waited for a long time and still have no output. This is the problem of low recursion efficiency. Recursion is to use the stack idea, calculate the previous value of the stack again and again, and then calculate the next value of the stack again and again. Finally, obtain the final value (the last value ). Therefore, we can know that a series of operations, such as the address of the function and the value of each parameter, need to be saved here, are definitely a waste of time and resources. Therefore, we need to find another way to solve this problem.

Most recursive problems can be solved through loops. Therefore, we can try to write the following circular code:

Function declaration:

ll DutFibonacci_2(int);

Function Definition:

Ll DutFibonacci_2 (int n) {if (n <= 0) return 0; else if (n = 1) return 1; ll one = 1; ll two = 0; ll result = 0;/* The non-recursive solution is also very simple. You can use two intermediate numbers to calculate the value that "used to exist" */for (int I = 2; I <= n; ++ I) {result = one + two; two = one; one = result;} return result ;}






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.