자바 피보나치 수열 출력하기

2019. 8. 6. 22:50Java/문풀

728x90

https://www.youtube.com/watch?v=WpzjpKt0lbc&list=PLVoihNyHW4xkm_KJ8_N8X7F6EQP4uSRyR&index=3

http://codingdojang.com/scode/461?orderby=time&langby=java

예) 0, 1, 1, 2, 3, 5, 8, 13..

n항까지 출력할 것인지 입력받아 피보나치 수열을 뽑아보자.

노가다 방법


package basic002;

import java.util.ArrayList;
import java.util.Scanner;

import javax.print.DocFlavor.INPUT_STREAM;

public class main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("몇 항까지 출력하시겠습니까?>> ");
        int num = scanner.nextInt();

        ArrayList<Integer> arr = new ArrayList<Integer>();

        if (num == 0) {
            arr.add(1);
            System.out.println(arr.get(0));
        } else if (num == 1) {
            arr.add(1);
            arr.add(1);
            System.out.println(arr.get(0));
            System.out.println(arr.get(1));
        } else {
            arr.add(1);
            arr.add(1);
            for (int i = 2; i <= num; i++) {
                arr.add(arr.get(i - 2) + arr.get(i - 1));
            }

            for (int i = 0; i < arr.size(); i++) {
                System.out.println(arr.get(i));
            }

        }

    }

}


728x90
반응형