본문 바로가기

Projects/백준 문제

Baekjoon 10872 java factorial

반응형

Recursive means, on a computer, repeatedly referring to yourself.

 

Because it calls method inside the method, there are some problems to consider.

 

  1. 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.

  2. 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.

반응형