β‘
Factorial
Factorialλ³΄ν΅ ν¨μ +20pts
Problem
Write a function that calculates the factorial of a number.
Examples
Input:
factorial(5)Output:
120π‘ 5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
Input:
factorial(0)Output:
1π‘ 0! = 1 (μ μ)
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)μ μ€ν κ³Όμ ** ``` ...
View detailed explanation βKey Concepts
μ¬κ· ν¨μ κΈ°μ 쑰건 μ¬κ· νΈμΆ ν©ν λ¦¬μΌ μν
Time: O(n) Space: O(n)
solution.js
Ctrl + Enter
Run tests to see results here.