forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.py
More file actions
18 lines (16 loc) ยท 611 Bytes
/
5.py
File metadata and controls
18 lines (16 loc) ยท 611 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ๋ฐ๋ณต์ ์ผ๋ก ๊ตฌํํ n!
def factorial_iterative(n):
result = 1
# 1๋ถํฐ n๊น์ง์ ์๋ฅผ ์ฐจ๋ก๋๋ก ๊ณฑํ๊ธฐ
for i in range(1, n + 1):
result *= i
return result
# ์ฌ๊ท์ ์ผ๋ก ๊ตฌํํ n!
def factorial_recursive(n):
if n <= 1: # n์ด 1 ์ดํ์ธ ๊ฒฝ์ฐ 1์ ๋ฐํ
return 1
# n! = n * (n - 1)!๋ฅผ ๊ทธ๋๋ก ์ฝ๋๋ก ์์ฑํ๊ธฐ
return n * factorial_recursive(n - 1)
# ๊ฐ๊ฐ์ ๋ฐฉ์์ผ๋ก ๊ตฌํํ n! ์ถ๋ ฅ(n = 5)
print('๋ฐ๋ณต์ ์ผ๋ก ๊ตฌํ:', factorial_iterative(5))
print('์ฌ๊ท์ ์ผ๋ก ๊ตฌํ:', factorial_recursive(5))