Programming of the "Fibonacci series"

Source: Internet
Author: User
Programming of the "Fibonacci series"

Today, I saw a mathematical concept about the "Fibonacci series" on the Internet. It's not too short for you to learn programming. You can use this stuff to practice it.

The Fibonacci series, also known as the Golden split series, refers to such a series: 1, 1, 2, 3, 5, 8, 13, 21 ,...... In mathematics, the Fibonacci series are defined as follows by recursive Methods: f0 = 0, F1 = 1, FN = f (n-1) + f (n-2) (N> = 2, n, N *) (from Baidu)

At the beginning, my programming code is as follows:

Function fbnq ($ num ){

If ($ num = 0 ){

Return 0;

} Elseif ($ num = 1 ){

Return 1;

} Else {

Return fbnq ($ num-2) + fbnq ($ num-1 );

}

}

$ Total = 10;

$ Arr = array ();

For ($ I = 0; $ I <$ total; $ I ++ ){

$ Arr [$ I] = fbnq ($ I );

Echo $ I. '--->'. $ arr [$ I]. '<br> ';

}

 

After compilation, I thought OK. After the result was changed to $ tatal to 25, I found that the operation was getting slower and slower. After running the program for 30 seconds, the system prompts that the running time is too long. It may be the efficiency of function design. At the beginning, I considered recursion. After N is greater than 3, each number is obtained through recursion. The greater the number of recursion times. Actually, recursion is not required at all. You only need to add the preceding calculation results. Therefore, it is okay to change $ Tata to 100 with the following code:

Function fbnq ($ num ){

Global $ arr;

If ($ num = 0 ){

Return 0;

} Elseif ($ num = 1 ){

Return 1;

} Else {

Return $ arr [$ num-2] + $ arr [$ num-1];

}

}

$ Total = 100;

$ Arr = array ();

For ($ I = 0; $ I <$ total; $ I ++ ){

$ Arr [$ I] = fbnq ($ I );

Echo $ I. '--->'. $ arr [$ I]. '<br> ';

}


Programming of the "Fibonacci series"

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.