2013년 10월 15일 화요일

[자바재귀호출]1부터임의수까지의 합(일반방식, 재귀방식)

[자바재귀호출]1부터임의수까지의 합(일반방식, 재귀방식)

 

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");
 }
}



2. 일반방식


class Sum1 {
 public static void main(String[] args) {
  if (args.length<1) {
   System.out.println("Usage : java Sum1 number ");
   System.exit(1);
  }
  long time = System.currentTimeMillis();
        int value = Integer.parseInt(args[0]);
  long hab=0;
  for(int i=1;i<=value;i++) {
   hab = hab + i;
  }
  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");
 }
}
  

[출처]오라클자바커뮤니티
http://www.oraclejavanew.kr/bbs/board.php?bo_table=C17&wr_id=164&page=2


오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의)  

[개강확정강좌]오라클자바커뮤니티에서 운영하는 개발자 전문교육 ,개인80%환급(www.onjprogramming.co.kr)




댓글 없음:

댓글 쓰기