Factorial
Factorial - Explanation
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
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size