The Fibonacci sequence refers to a sequence of 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ...
This sequence starts with the 3rd item and each item is equal to the sum of the first two items.
1. Recursive algorithm:
function fib (n) { if2) { return n; } Else { return fib (n-1) + fib (n-2);} }
2. Dynamic Programming Algorithms
function fib (n) {varval = []; for(vari =0; I <= N; ++i) {Val[i]=0; } if(n = =1|| n = =2) { return 1; }Else{val[1] =1; val[2] =2; for(vari =3; I <= N; ++i) {Val[i]= val[i-1] + val[i-2]; } returnval[n-1]; } }
The reason why a dynamic plan needs to use an array is because the dynamic programming algorithm usually needs to save the intermediate results. Dynamically planned solutions are more efficient than recursive solutions when calculating fib (20) and larger numbers.
3. Iterative method
function fib (n) { var1; var 1 ; var 1 ; for (var2; i < n; + +i) {= last + nextlast ; = Last ; = result; } return result; }
JS Fibonacci sequence