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"