JS Implementation of factorial and Recursion
At first glance, it is indeed very easy to implement factorial by recursion, but it still requires a little skill to implement recursion well.
Recursion means that the program continuously calls its own programming skills during execution. Of course, there must also be a clear termination condition. Otherwise, it won't be able to stop ~ Here we can simply implement recursive factorial.
- function factorial( n ){
- return ( n <= 1 ) ? 1 : n * factorial( n-1 );
- }
For factorial recursion, because it only calls itself once each time, it will not cause some major problems, but for some relatively complex recursion, it is necessary to do some technical caching. For example, the most typical use case of recursion is to calculate the Fibonacci series, but each call will call its own function twice here. So, 2 to 4, 4 to 8, and the magnitude increases exponentially, when calculating a slightly larger number, some running time may occur, or may cause stack overflow.
- function fibonacci( n ){
- return ( n <= 2 ) ? 1 : fibonacci( n-1 ) + fibonacci( n-2 );
- }
- function t(n){
- console.time("a");
- console.log( fibonacci( n ));
- console.timeEnd("a");
- }
The above is the specific data. It seems that there is a significant consumption point. After all, it takes 2 s to reach 42. After all, the tested host is considered as a superior, to optimize the caching method, try the following:
- var fibArr = [ undefined, 1, 1 ];
- function fibonacci( n ){
- var nFib = fibArr[ n ];
- return nFib
- ? nFib
- : ( fibArr[ n ] = fibonacci( n-1 ) + fibonacci( n-2 ) );
- }
Well, there is not much explanation. This is the result of optimization. Think about it and we can feel that we have reduced the computing magnitude of the Fibonacci number from the secondary index of 2 to the secondary index of the constant n, and because of the cache, the magnitude of operation will be reduced in multiple times, then I was shocked by the running speed. This method also relieves stack overflow.
If you remember correctly, there is a theory that all recursive loops can be converted into iterative loops.
- function fibonacci( n ){
- var x = 1, y = 1, i=2, t;
- while( i < n ){
- t = y;
- y = x + y;
- x = t;
- i++;
- }
- return y;
- }
It seems that this is a little more awesome. In fact, its magnitude is the same as that of the recursive formula with cache after optimization, but his amount is only calculated, and every amount of recursion calls a method, this is also the biggest difference between the two.
Well, let's just give a brief look at our own views. We need to think carefully about the recursive method. If it is difficult to play a game, we will be paralyzed. If you are not professional, please forgive me. If you have any mistakes, please correct me. Thank you.