2013년 12월 27일 금요일

자바 재귀호출(Java Recursion Call), 재귀호출,Divide and Conquer이란(JAVA재귀호출예제)

자바 재귀호출(Java Recursion Call), 재귀호출,Divide and Conquer이란(JAVA재귀호출예제)
 
메소드가 직/간접적으로 자기 메소드를 호출하는것을 이야기 한다.

복잡한 논리를 간결하게 프로그래밍 가능,알고리즘이 간결해지며, 시스템 스택 메모리를 사용한다.

효율성의 문제가 대두 되는 경우엔 반복적인 방법으로 푼다.

재귀호출로 코드 작성시 종료 조건을 명시하여 반드시 출구를 기술해야 한다. 안그러면 걔속 호출되므로 스택 메모리 오류발생!!

문제의 크기가 직접 해결할 수 있을 정도로 작아 졌을 때 Base Case라고 한다.
 
참고

- Divide and Conquer

큰 문제를 작은 문제로 나누어서 해결함으로서 결국 큰 문제를 해결하는 방법
 
막대가 100개 있다고 할 때, 처음 막대는 직접 밀었으니 반드시 쓰러진다. 또 막대기의 길이가 막대기간 간격보다 크므로 N번째 막대가 쓰러지면 N+1번째 막대도 반드시 쓰러진다. 이 두가지 사실에 근거하여 N=1이 쓰러지고 N=2도 쓰러지고 ... 최종적으로 100번째 막대도 쓰러진다.

[1부터 임의의 수까지 합을 재귀 호출로]
 
수행시간 및 메모리 사용 현황도 출력 했습니다.
 
class Sum {
long hab(int value) {
if(value == 0) return 0;
else return value+hab(value-1);
}
public static void main(String[] args) {
if (args.length<1) {
System.out.println("Usage : java Sum number ");
System.exit(1);
}
long time = System.currentTimeMillis();
        int value = Integer.parseInt(args[0]);
Sum s = new Sum();
long hab = s.hab(value);
System.out.println("1부터 " + value + " 까지 합 = " + hab);
System.out.println("총 소요시간 : " + (System.currentTimeMillis()-time) + " millis");
Runtime r = Runtime.getRuntime();
long t = r.totalMemory();
long f = r.freeMemory();
System.out.println("총 메모리 : " + t + " bytes");
System.out.println("남은 메모리 : " + f  + "bytes");
}
}

[재귀호출을 이용하여 팩토리얼 구하기]
 
4! = 4 * 3 * 2 * 1 = 24
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!

import java.io.*;
public class FactorialRecursion{
 private static int result;
 public static int factori(int n){
  if(n == 1){
   result  = 1;
  }
  else
   result = n*factori(n-1);
  return result;
 }
 public static void main(String[] args) throws IOException{
  BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
  int num;
  System.out.println("===Use the recursion===============");
  System.out.print("Put into the N : ");
  System.out.flush();
  num = Integer.parseInt(stdin.readLine());
  System.out.println("N! : " + factori(num));
 }
}

댓글 없음:

댓글 쓰기