반응형

package com.example.recursive;

/*

 * 재귀(귀납) - Recursive

 * 메소드가 자기 스스로를 끊임없이 호출하는 과정을 의미한다.

 * 그것을 재귀메소드라 칭한다.

 * 

 * syntax

 * 

 * returntype methodname(){

 * methodname();

 *  

 */


public class RecursiveExample {

static void p() {

System.out.println("P has called");

p();

}


public static void main(String[] args) {

p();

}

}  

몇번돌다가 에러를 뱉을겁니다.. 재귀하면 떠오르는 StackOverFlow!!

///////////////////////////////////////////////////////////////


package com.example.recursive;



public class RecursiveExample2 {


static int factorial(int n) {

// static method

if (n == 1)

return 1;

else

return (n * factorial(n - 1));

// 2이상의 값이 들어올 경우 위 구문이 진행된다./

//그리고 n-1한 값을 다시 factorial에 넣고 돌린다.

// 그러다 n이 1이 되면 1을 리턴합니다.

// 원리는 아래와 같습니다.

// factorial(5) 

                       factorial(4) 

                             factorial(3) 

                                 factorial(2) 

                                        factorial(1) 

                                               return 1 

                                    return 2*1 = 2 

                             return 3*2 = 6 

                             return 4*6 = 24 

                       return 5*24 = 120

//return안에서 factorial메소드가 파라미터가 1이 될때까지

//돌고난 후 return을 통해 값이 출력되는데 태엽을 상상하시면 이해가

// 쉬울것같습니다.

}


public static void main(String[] args) {

System.out.println("Factorial of 5 is: " + factorial(5));


}

}

//////////////////////////////////////////////////////////////////

public class RecursiveExample3 {


static int count = 0;


static void p() {

count++;

if (count <= 9) {

System.out.println("hello " + count);

p();

}

}


public static void main(String[] args) {

p();

}

}

result = 

hello 1

hello 2

hello 3

hello 4

hello 5

hello 6

hello 7

hello 8

hello 9


//////////////////////////////////////////////////////////////////

// 파보나치 수열!

public class RecursiveExample4 {

static int n1 = 0, n2 = 1, n3 = 0;


static void printFibo(int count) {

if (count > 0) {

n3 = n1 + n2;

n1 = n2;

n2 = n3;

System.out.print(" " + n3);

printFibo(count - 1);

}

}


public static void main(String[] args) {

int count = 15;

System.out.print(n1 + " " + n2);// printing 0 and 1

printFibo(count - 2);// n-2 because 2 numbers are already printed

}

}

result = 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377




반응형
by 발전소장 에르 :) 2017. 9. 25. 17:37
| 1 |