๐ŸŒป JAVA/์•Œ๊ณ ๋ฆฌ์ฆ˜, ์ž๋ฃŒ๊ตฌ์กฐ

์•Œ๊ณ ๋ฆฌ์ฆ˜ - ์žฌ๊ท€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (feat. Factorial, Fibonacci)

iseunghan 2020. 11. 16. 17:02
๋ฐ˜์‘ํ˜•

์žฌ๊ท€(Recursion) ์ด๋ž€ ๋ฌด์—‡์ผ๊นŒ? 

์–ด๋Š ํ•œ ์ปดํ“จํ„ฐ๊ณตํ•™๊ณผ ํ•™์ƒ์ด ์œ ๋ช…ํ•œ ๊ต์ˆ˜๋‹˜์„ ์ฐพ์•„๊ฐ€ ๋ฌผ์—ˆ๋‹ค.

"์žฌ๊ท€ํ•จ์ˆ˜๊ฐ€ ๋ญ”๊ฐ€์š”?"
"์ž˜ ๋“ค์–ด๋ณด๊ฒŒ. ์˜›๋‚ ์˜›๋‚  ํ•œ ์‚ฐ ๊ผญ๋Œ€๊ธฐ์— ์ด์„ธ์ƒ ๋ชจ๋“  ์ง€์‹์„ ํ†ต๋‹ฌํ•œ ์„ ์ธ์ด ์žˆ์—ˆ์–ด. ๋งˆ์„ ์‚ฌ๋žŒ๋“ค์€ ๋ชจ๋‘ ๊ทธ ์„ ์ธ์—๊ฒŒ ์ˆ˜๋งŽ์€ ์งˆ๋ฌธ์„ ํ–ˆ๊ณ , ๋ชจ๋‘ ์ง€ํ˜œ๋กญ๊ฒŒ ๋Œ€๋‹ตํ•ด ์ฃผ์—ˆ์ง€. ๊ทธ์˜ ๋‹ต์€ ๋Œ€๋ถ€๋ถ„ ์˜ณ์•˜๋‹ค๊ณ  ํ•˜๋„ค.
๊ทธ๋Ÿฐ๋ฐ ์–ด๋Š ๋‚ , ๊ทธ ์„ ์ธ์—๊ฒŒ ํ•œ ์„ ๋น„๊ฐ€ ์ฐพ์•„์™€์„œ ๋ฌผ์—ˆ์–ด.

"์žฌ๊ท€ํ•จ์ˆ˜๊ฐ€ ๋ญ”๊ฐ€์š”?"
"์ž˜ ๋“ค์–ด๋ณด๊ฒŒ. ์˜›๋‚ ์˜›๋‚  ํ•œ ์‚ฐ ๊ผญ๋Œ€๊ธฐ์— ์ด์„ธ์ƒ ๋ชจ๋“  ์ง€์‹์„...

์ถœ์ฒ˜ : namu.wiki/w/%EC%9E%AC%EA%B7%80%ED%95%A8%EC%88%98

 

 

ํŒฉํ† ๋ฆฌ์–ผ๋กœ ์•Œ์•„๋ณด๋Š” ์žฌ๊ท€ ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

๋จผ์ € ํŒฉํ† ๋ฆฌ์–ผ ์ด๋ž€?

์ˆซ์ž n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, n ๋ถ€ํ„ฐ 1๊นŒ์ง€์˜ ๊ณฑ์˜ ๊ฒฐ๊ณผ๋ฅผ ๋œปํ•œ๋‹ค.

0! = 1
1! = 1
2! = 2 x 1
3! = 3 x 2 x 1
..
n! = n x (n-1) x  ...  x 1

 

 

 

์ด๊ฒƒ์„ ํŠธ๋ฆฌ ํ˜•ํƒœ๋กœ ๋งŒ๋“ค๋ฉด, ์•„๋ž˜์˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™๋‹ค.

์ž ๊ทธ๋Ÿผ ์ด์ œ ์ ํ™”์‹์ด ๋ณด์ธ๋‹ค. 

if (n==1) ์ผ ๊ฒฝ์šฐ ∫(n) = 1;
if (n==2) ์ผ ๊ฒฝ์šฐ ∫(n) = 1;
n์€ 0๋ณด๋‹ค ํฐ ์–‘์˜ ์ •์ˆ˜์ด๋‹ค.

∫(n)=  n x ∫(n-1)

 

 

์ฝ”๋“œ๋กœ ํ‘œํ˜„ ํ•ด๋ณด์ž.

 

import java.util.Scanner;

public class Factorial_10872 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int result = factorial(N);
        System.out.println(result);
    }

    private static int factorial(int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }
}

 


 

ํ”ผ๋ณด๋‚˜์น˜๋กœ ์•Œ์•„๋ณด๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์ด๋ž€?

์ถœ์ฒ˜ : ko.wikipedia.org/wiki/%ED%94%BC%EB%B3%B4%EB%82%98%EC%B9%98_%EC%88%98

 

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์„ ํ•œ๋ฒˆ ์ž์„ธํžˆ ๋ณด์ž.

 

์ ํ™”์‹์„ ์ž‘์„ฑ ํ•ด ๋ณด์ž.

if(n==0 ) ์ผ๋•Œ, ∫(0) = 0;
∫(1) = 1;
∫(2) = 1;

n > 2 ๋ฅผ ๋งŒ์กฑํ•˜๋Š” ์–‘์˜ ์ •์ˆ˜์— ๋Œ€ํ•˜์—ฌ

∫(n)=  ∫(n-1) + ∫(n-2)

 

์ฝ”๋“œ๋กœ ์ž‘์„ฑํ•˜๋ฉด,

import java.util.Scanner;

public class Fibonacci {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int result = fibonacci(N);
        System.out.println(result);
    }

    private static int fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 1;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
๋ฐ˜์‘ํ˜•