21.08.06 기록
백준 알고리즘 10872 풀이
🎆나의 풀이(메모리 14.1MB, 시간 148ms로 통과)
-습관적으로 for문으로 풀이했다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B10872 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int res = 1;
for(int i = 1; i <= N; i++) {
res *= i;
}
System.out.println(res);
}
}
🎆해설(메모리 14.2MB, 시간 136ms로 통과)
-풀이를 보고 재귀 함수로 풀 수 있다는 것을 상기할 수 있었다.
- 재귀의 호출이 많아지면 자바에서는
StackOverFlow오류가 뜬다.- 재귀함수는 반복적으로 호출하는만큼 메모리의 스택이 되기 때문에 메모리를 많이 차지하고,
재귀함수가 끝날 때는 메모리에서 pop하면서 수행시간이 느려진다.- 재귀는 끝나는 지점이 명확하지 않으면 무한루프에 빠지기 쉬우니,
끝나는 지점을 정확하게 구현해야한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B10872 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int res = factorial(Integer.parseInt(br.readLine()));
System.out.println(res);
}
public static int factorial(int N) {
if(N <= 1) { return 1; }
return N * factorial(N-1);
}
}