반응형
Recursive means, on a computer, repeatedly referring to yourself.
Because it calls method inside the method, there are some problems to consider.
- If the recursive call becomes too repetitive, that is, when the recursive deepens, Java spits out an error called Stack Overflow. In the case of a recursive function, it eventually takes up a huge amount of memory because it is stacked in memory as much as the function is repeatedly called. And at the end of the recursive function, the execution time is also very slow because the function is popped in the stacked memory while closing it. In the end, recursive calls are usually used when the algorithm itself is natural or within the range of not making many calls because it is common to run out of memory and to deteriorate performance.
- The point where the recursive function ends must be accurately implemented. This is natural, but especially in recursive, if the end point is not clear, it is easy to fall into an infinite loop.
Most of the recursive problems are solved by for and while iteration.
package bj10872;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
System.out.println(factorial(N));
}
public static int factorial(int N) {
if(N <= 1) return 1; // recursive end condition
return N * factorial(N - 1);
}
}
When N becomes 1 or 0, return 1 else, operate N * factorial(N-1) so it constructs recursive function.
반응형
'Projects > 백준 문제' 카테고리의 다른 글
백준 11654 자바 문제 아스키코드 변환 (0) | 2022.02.21 |
---|---|
Baekjoon 10870 Java Recursive Fibonacci number (0) | 2022.02.20 |
백준 15596번 자바 문제 (0) | 2022.02.07 |
백준 3444번 자바 문제 평균은 되겠지 (0) | 2022.02.07 |
백준 8958번 자바 문제 OX퀴즈 (0) | 2022.02.07 |