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);
}

'JAVA > 알고리즘' 카테고리의 다른 글

BFS(레벨탐색) 예제  (0) 2021.06.16
피보나치 수열 (반복문, DFS)  (0) 2021.06.09
2진수 변환 (반복문, 재귀함수)  (0) 2021.06.09
자연수 출력 (반복문, 재귀함수)  (0) 2021.06.09
이진탐색  (0) 2021.06.08