http://www.jstips.co/en/javascript/recursion-iteration-and-tail-calls-in-js/

 

Recursion, iteration and tail calls in JS

If you’ve been on the business for some time, you have, most likely, come across the definition of recursion, for which the factorial of a given number n! = ...

www.jstips.co

 

재귀 ( Recursion, factorial function )

function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

예제에서 n이 6일 때 아래처럼 동작한다.

factorial(6)
  6 * factorial(5)
    5 * factorial (4)
      4 * factorial(3)
        3 * factorial(2)
          2 * factorial(1)
            1 * factorial(0)
            	1
            (resuming previous execution) 1 * 1 = 1
          (resuming…) 2 * 1 = 2
        (…) 3 * 2 = 6
      … 4 * 6 = 24
    5 * 24 = 120
  6 * 120 = 720
factorial(6) = 720

 

재귀 함수는 일단 끝까지 다 스텍에 쌓아놓고 안 쪽 부터 리턴된 값고 함께 스텍을 풀어나간다.

재귀를 빠져나올 조건을 잘 걸어줘야 한다. 안 그러면 스텍 사이즈오버 에러 나온다.

+ Recent posts