Factorial

Factorial - Explanation

보통 함수 O(n) O(n)

Problem Summary

Write a function that calculates the factorial of a number.

Go to Problem →

Detailed Explanation

이 문제는 **재귀 함수**의 기본 개념을 학습합니다. 팩토리얼은 재귀의 대표적인 예시입니다. **팩토리얼의 수학적 정의** - n! = n × (n-1) × (n-2) × ... × 1 - 0! = 1 (수학적 정의) - 1! = 1 **재귀의 핵심 요소** 1. **기저 조건(Base Case)**: 재귀를 멈추는 조건 - n <= 1일 때 1을 반환 2. **재귀 호출(Recursive Case)**: 자기 자신을 호출 - n * factorial(n - 1) **factorial(5)의 실행 과정** ``` factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 * factorial(1) = 5 * 4 * 3 * 2 * 1 = 120 ``` **반복문 버전** ```javascript function factorial(n) { let result = 1; for (let i = 2; i <= n; i++) result *= i; return result; } ``` 재귀는 코드가 직관적이지만, 반복문이 메모리 효율적입니다.

Solution Code

solution.js
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

Key Concepts from This Problem

1. 재귀 함수
2. 기저 조건
3. 재귀 호출
4. 팩토리얼 수학

Common Mistakes

기저 조건을 빠뜨리면 무한 재귀로 스택 오버플로우가 발생합니다
n * factorial(n)처럼 n을 줄이지 않으면 무한 루프입니다
음수 입력에 대한 처리가 없으면 무한 재귀가 발생합니다

Hints

Hint 1: 재귀 함수를 사용해보세요.
Hint 2: 기저 조건: n이 0 또는 1이면 1을 반환합니다.
Hint 3: 반복문으로도 구현할 수 있습니다.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#함수 #재귀 #수학