The Fibonacci sequence can be roughly describe as a (n) = A (n-1) + A (n-2) (a >=2). Similar to this [1, 1, 2, 3, 5, 8, 13 ...].
Specific we can Baidu a bit. Let's use JS to get the nth number of Fibonacci sequence numbers:
1. Recursion
var function (n) { if (n = = 1 | | n = = 2) { return 1 else { c12/>return A (n-1) + A (n-2) } } console.time (' A () ') Console.log (A ()) console.timeend (' A (44) ')
Above we can clearly see the code of thought, but this method has a fatal disadvantage: the efficiency is too poor!
Don't believe you see:
By the time the 44th was executed, it was unacceptable. Requires more than 5s. Well, let's make it a little bit better.
--------------------------------------------------------------------------------
2. Closures + Caching
varB = (function() { varCache = { 1:1, 2:1 } return function(n) {if(Cache[n]) {returnCache[n]}Else{cache[n-1] = B (n-1) Cache[n-2] = B (n-2) returnCache[n-1] + cache[n-2]}}) () Console.time (' B (1200) ') Console.log (b (1200)) Console.timeend (' B (1200) ')
The values calculated for each step are saved in the cache. Efficiency has improved a lot:
------------------------------------------------------------------
3. Directly calculate the value of the array, and then take the values from the array
var c = function (n) { var arr = [1, 1] if (n = = 1 | | n = = 2return 1} for (var i = 2; i < n; I ++ = arr[i-1] + arr[i-2]} return arr[n-1]} console.time ( ' C (+) '
) Console.log (c (
1200 ' C (+) ')
This efficiency has been further improved a lot:
So is there a quicker way to do that? Of course! The Fibonacci series is mathematically expressed:
Why don't we just use mathematical expressions?
-----------------------------------------------------
4. Direct use of mathematical expressions
var function (n) { return (1/(Math.pow (5))) * (Math.pow ((1 + math.pow (5))/2, N)-Math.pow ((1-math.po W (5, I))/2, N) } console.time (' d () ') Console.log (d ()) Console.timeend (' d (1200) ')
Now let's look at the effect:
So sum up: math is so beautiful! ^_^
JS gets the nth element of the Fibonacci sequence