- Notifications
You must be signed in to change notification settings - Fork 846
/
Copy path5.cpp
27 lines (23 loc) · 730 Bytes
/
5.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<bits/stdc++.h>
usingnamespacestd;
// 반복적으로 구현한 n!
intfactorialIterative(int n) {
int result = 1;
// 1부터 n까지의 수를 차례대로 곱하기
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// 재귀적으로 구현한 n!
intfactorialRecursive(int n) {
// n이 1 이하인 경우 1을 반환
if (n <= 1) return1;
// n! = n * (n - 1)!를 그대로 코드로 작성하기
return n * factorialRecursive(n - 1);
}
intmain(void) {
// 각각의 방식으로 구현한 n! 출력(n = 5)
cout << "반복적으로 구현:" << factorialIterative(5) << '\n';
cout << "재귀적으로 구현:" << factorialRecursive(5) << '\n';
}