Php Chinese Network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Input n to obtain the nth entry of the Fibonacci series.
Function fibonacci (n) {if (n <0) {throw new Error ('input number cannot be less than 0');} if (n = 0) {return 0 ;} if (n = 1) {return 1;} return fig (n-1) + fig (n-2 );}
This is not a good method.
For example, in the case of fibonacci (10), it is broken down into fibonacci (9) and fibonacci (8), but fibonacci (9) is broken down into fibonacci (8) and fibonacci (7 ), here, we repeat the calculation of fibonacci (8), and so on. There are many repeated calculations. The simplest way is to record the calculated values:
Function fibonacci2 (n) {if (n <0) throw new Error ('input number cannot be less than 0'); let arr = [0, 1]; function calc (n) {if (n <2) {return arr [n];} if (arr [n]! = Undefined) {return arr [n];} let data = calc (n-1) + calc (n-2); arr [n] = data; return data ;} return calc (n);} function fibonacciFunc () {let arr = [0, 1]; function calc (n) {if (n <0) throw new Error ('input number cannot be less than 0'); if (n <2) return arr [n]; if (arr [n]! = Undefined) {return arr [n];} let data = calc (n-1) + calc (n-2); arr [n] = data; return data;} return calc ;} let maid ();
The closure is used in the above two methods.
The disadvantage of fibonacci3 is that as long as fibonacci3 is not released, the arr array in the memory will always exist. Especially after a relatively large number is computed, but when a large number of fibonacci numbers are required, fibonacci3 will be advantageous, but remember to release the final release of fibonacci3, that is:
fibonacci3 = null;
Another method is to directly loop without recursion.
Function fibonacci4 (n) {if (n <0) throw new Error ('input number cannot be less than 0'); let dataMinusTwo = 0, dataMinusOne = 1, data; if (n = 0) return dataMinusTwo; if (n = 1) return dataMinusOne; for (var I = 2; I <= n; I ++) {data = dataMinusOne + dataMinusTwo; dataMinusTwo = dataMinusOne; dataMinusOne = data ;}return data ;}
The above is the js Implementation of the Fibonacci series content. For more information, please follow the PHP Chinese Network (www.php1.cn )!