본문 바로가기
JAVA

피보나치수열 재귀

by Son 2021. 5. 11.

입력된 항의 피보나치 수를 구하시오

 

6(1 1 2 3 5 8)

 

조건 재귀함수를 사용하여 피보나치 수를 구하시오

 

package_34_Fibonacci_numbers;

 

import java.util.Scanner;

 

public static pibo(int N){

 

   if (N ==1)

             return 1;  // 피보나치 수열에서 첫 값은 1

   if(N == 2)

             return 1;  // 피보나치 수열에서 두번째  값은 1

 

   return pibo(n-2)+ pibo(n-1);            //3번째 값은 pibo(1)+pibo(2)  4번째 값은 pibo(2)+pibo(3)

                                                   //즉 규칙은 pibo(n-2)+pibo(n-1)

 

}

 

public static void main(String[] args){

 

    Scanner scan = new Scanner(System.in); //수 입력

    int N =scan.nextInt(); //정수를 입력받고 그 정수를 N에 저장

   

    int ans = pibo(N); //재귀함수 pibo(N)을 ans 값에 저장

 

    System.out.println(ans); //ans출력

    

    

    }

 

 

}