JAVA/JAVA Algorithm

[백준 10870번] 피보나치 수열 문제

오늘의 진 2023. 3. 14. 23:16

n번째피보나치 수를 구하는 프로그램을 작성하시오 

 

첫번째 줄에 n이 주어진다. n은 20보다 작거나 같은 자연수 

 

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

규칙성이 존재

재귀호출로 간단하게 해결 

import java.util.Scanner;

public class Main {



    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
        System.out.println(function(n));

    }



    public static int function(int n){
        if (n <=1){
            return  n;
        }
        return function(n-1) + function(n-2);
    }

}