JAVA/알고리즘
팩토리얼 (반복문, DFS)
lovineff
2021. 6. 9. 10:36
자연수 N이 입력되면 N!를 구하는 프로그램을 작성하세요.
예를 들어 5! = 5*4*3*2*1=120입니다.
▣ 입력설명
첫 번째 줄에 자연수 N(1<=N<=100)이 주어집니다.
▣ 출력설명
첫 번째 줄에 N팩토리얼 값을 출력합니다.
▣ 입력예제 1
5
▣ 출력예제 1
120
public static void main(String[] args) {
int N = 5;
int i = solutionByIterator(N);
System.out.println(i);
int n = solutionByDFS(N, 1);
System.out.println(n);
}
private static int solutionByIterator(int n) {
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
}
return result;
}
private static int solutionByDFS(int n, int result) {
if(n == 0){
return result;
}
return solutionByDFS(n-1, result * n);
}