forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5.java
29 lines (24 loc) Β· 869 Bytes
/
5.java
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));
}
}