javascript recursive algorithm ---

"To understand recursion, you must first understand recursion." - Anonymous

Is a recursive function calls itself within the function can be a function or a method, directly or indirectly .

What assumptions have a function call itself a result? Solely on the above, it would have been implemented. Therefore, each recursive function must have a baseline condition, a condition that is no longer recursive call (stopping point), in order to prevent infinite recursion. 

A function (X-) {    
  const recursionAnswer = Confirm ( 'recursion Understand the Do you?');
IF (recursionAnswer === to true) {
    // baseline conditions, stopping point
   return to true;
 }
  // recursive call
  A (recursionAnswer);
}

As a first example of recursion, we look at how to calculate the factorial of a number. Factorial of the number n, is defined as the product of n represents an integer !, from 1 to n.
5 represents the factorial of 5 !, and 5 × 4 × 3 × 2 × 1 are equal, the result is 120. (Note that a concept definition 0! = 1, is not equal to 0)

factorial function (X) {
     // baseline 
    IF (X == 0 || == X . 1 ) {
        return  . 1 ;   
    } 
    // recursive call 
    
    return     X * factorial (X- . 1 ); 

}

Fibonacci number

 Sequence 0,1,1,2,3,5,8,13,21, 34, etc. the number thereof. Number 1 2 + 1 is obtained from the number obtained from the 3 1 + 2, Number 5 + 2 obtained from 3, and so on. Fibonacci number is defined as follows. 

 

 

// iterative method

function fibonacciIterative(n) {  
       if (n < 1) return 0;
       if (n <= 2) return 1; 
       let fibNMinus2 = 0;  
       let fibNMinus1 = 1;  
       let fibN = n;  
       for (let i = 2; i <= n; i++) { 
             // n >= 2 
            fibN = fibNMinus1 + fibNMinus2; 
            // f(n-1) + f(n-2)   
            fibNMinus2 = fibNMinus1;  
            fibNMinus1 = fibN;  
       }   
  return fibN; 
} 
                       

// recursive method

function fibona(n){
    if(n <= 2)
    {
        return 1;
    }
    if(n < 1)
    {
        return 0;
    }
    reurn fibona(n-1)+fibona(n-2);
}

Guess you like

Origin www.cnblogs.com/elexmiumiu/p/12206512.html