티스토리 뷰

Algorithms

Recursion in Java

seoca 2019. 7. 24. 02:40

 

 

Recursion in Java 재귀호출

 

In programming, It's common to call a method from another method.

Recursion allows calling the method itself. A factorial example is a popular way to understand the basic principle of recursion.

재귀함수는 재귀를 종료시킬 조건에 부합할 때까지 자기 자신의 메서드를 계속 호출하기 때문에 종료조건에 다다르고 나서야 값을 리턴하기 시작한다. 

 

factorial 

5! = 5 x 4 x 3 x 2 x 1

5! = 5 x 4!

4! = 4 x 3 x 2 x 1

4! = 4 x 3!

 

 

factorial using loop

public class Main {
    public static void main(String[] args) {
        int f=1;
        int number=5;
        
        for(int i=1 ; i<=number ; i++){
            f = f * i;
        }
        
        System.out.println("Factorial of "+number+" is: "+f);//Factorial of 5 is: 120
    }
}
 

 

 

factorial using recursion 

 

public class Main {
    public static void main(String[] args) {
        int k = 3;
        System.out.println("Factorial of " + k + " is " + factorial(k)); //Factorial of 3 is 6
    }
 
    private static int factorial(int i){
        if(i == 1){
            return i;
        }else{
            int j = i * factorial(i - 1);
            return j;
        }
    }
}
 

 

  3 x (3-1) 2 x (2-1) 1 x (1) 반환시작
return 3 x 2 = 6 2 x 1 = 2 1

 

 

recursion example - Calculate the power of a number using recursion 

2의 n승을 계산하는 재귀함수

 

public class Main {
    public static void main(String[] args) {
        int k = 4;
        System.out.println(2 + " to the power of " + k + " is " + num(k)); //2 to the power of 4 is 16
    }
 
    private static int num(int i){
        if(i == 0){
            return 1;
        }
        return 2 * num(i-1);
    }
}
 

 

'0' 즉, 재귀종료 조건에 다다르면 리턴을(리턴 값 '1') 시작한다.

  2 x (4-1) 2 x (3-1) 2 x (2-1) 2 x (1-1) 2 x (0) 반환시작
return 2 x 8 = 16 2 x 4 = 8 2 x 2 = 4 2 x 1 = 2 1

 

 

 

 

Reference

https://deftkang.tistory.com/36

'Algorithms' 카테고리의 다른 글

Selection Sort  (0) 2019.07.27
Bubble Sort  (0) 2019.07.25
Binary Search  (0) 2019.07.23
완주하지 못한 선수 - Hash  (0) 2019.07.23
Programmers 핸드폰번호 가리기  (0) 2019.03.03