[Algorithm]BJ_10872 팩토리얼

dnjsrms.lee·2022년 6월 3일
0

Algorithm

목록 보기
3/3
post-thumbnail

[BJ_10872]팩토리얼 | 누르면 해당 문제로 이동

재귀

재귀란❓
함수안의 함수를 계속해서 호출하는 것이다.

재귀함수를 사용 할 때에는 주의사항이 있다.
1. 재귀함수를 호출 시 매개변수, 리터 값 등을 스택에 저장하는데 재귀함수는 연속적으로 함수를 호출하기에 stack에 메모리가 계속해서 쌓이게 된다.
2. 함수의 끝을 return을 통해 끝을 내줘야 함. 그렇지 않으면 Stack OverFlow라는 에러가 나타남.
3. 메모리 부족은 곧 성능의 저하를 일으킴으로 주의할 것.

재귀함수와 반복문을 통해 쉽게 풀 수 있다.

재귀함수

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BJ_10872 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        int result = factorial(N);
        System.out.println(result);
    }

    private static int factorial(int N) {
        if(N<=1){
            return 1;
        }else {
            return N*factorial(N-1);
        }
    }
}

0!=1 이므로 N이 1과 0일 때 return 1을 해주면 된다.

반복문

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
 
public class BJ_10872 {
 
	public static void main(String[] args) throws IOException {
 
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		
		int sum = 1;
        
		// N 이 0이 아닐 때 까지 1씩 감소하면서 sum에 반복적으로 곱해준다
		while(N != 0) {
			sum = sum * N;
			N--;
		}
        
		System.out.println(sum);
		
	}
}
profile
little by little slowly

0개의 댓글