재귀호출 (recursive call)은 메써드 내에서 자기자신을 반복적으로 호출하는 것으로 팩토리얼 계산 등에서 사용되는데 메모리를 과다하게 사용해서 성능저하와 Stack overflow가 발생하기 쉬워서 권장하지 않는다. 5!=5*4*3*2*1, f(n)=n*f(n-1)식으로 표시된다.
package java0810;
public class Test17 {
static long fact1(int n) {
return n==1 ? 1 : n*fact1(n-1); // Recursive calling
}
static long fact2(int n) {
long result = 1;
for (int i=1; i<=n; i++) {
result = result*i; // General calling
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fact1(5));
System.out.println(fact2(25));
}
}
댓글