forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.java
More file actions
29 lines (24 loc) ยท 869 Bytes
/
5.java
File metadata and controls
29 lines (24 loc) ยท 869 Bytes
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
28
29
import java.util.*;
public class Main {
// ๋ฐ๋ณต์ ์ผ๋ก ๊ตฌํํ n!
public static int factorialIterative(int n) {
int result = 1;
// 1๋ถํฐ n๊น์ง์ ์๋ฅผ ์ฐจ๋ก๋๋ก ๊ณฑํ๊ธฐ
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// ์ฌ๊ท์ ์ผ๋ก ๊ตฌํํ n!
public static int factorialRecursive(int n) {
// n์ด 1 ์ดํ์ธ ๊ฒฝ์ฐ 1์ ๋ฐํ
if (n <= 1) return 1;
// n! = n * (n - 1)!๋ฅผ ๊ทธ๋๋ก ์ฝ๋๋ก ์์ฑํ๊ธฐ
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
// ๊ฐ๊ฐ์ ๋ฐฉ์์ผ๋ก ๊ตฌํํ n! ์ถ๋ ฅ(n = 5)
System.out.println("๋ฐ๋ณต์ ์ผ๋ก ๊ตฌํ:" + factorialIterative(5));
System.out.println("์ฌ๊ท์ ์ผ๋ก ๊ตฌํ:" + factorialRecursive(5));
}
}