Help us understand the problem. What is going on with this article?

Javaでフィボナッチ数列を表示

More than 5 years have passed since last update.

Javaを使ってフィボナッチ数列を表示してみました。
エディタはSublime Text3を使用
行数:26(空白行を含む,コメントは除く)

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

public class Fibonacci{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        System.out.println("x番目までのフィボナッチ数を表示します");
        int x = scan.nextInt();

        long oldNum1 = 0;
        long oldNum2 = 1;
        long fibonacciNum = 1;

        ArrayList<Long> fibData = new ArrayList<Long>();

        System.out.println("----- Fibonacci_Numbers -----");

        for(int i = 0; i < x; i++){
            fibData.add(fibonacciNum);
            System.out.println(fibData.get(i));
            fibonacciNum = oldNum1 + oldNum2;
            oldNum1 = oldNum2;
            oldNum2 = fibonacciNum;
        }

        /* 

        long fibonacciNums[] = new long[x];

        if(x <= 2){
            for(int i = 0; i < x; i++){
                System.out.println("1");
            }

            return;
        }

        fibonacciNums[0] = 1;
        fibonacciNums[1] = 1;

        System.out.println(fibonacciNums[0]);
        System.out.println(fibonacciNums[1]);

        for(int i = 2; i < x; i++){
            fibonacciNums[i] = fibonacciNums[i-1] + fibonacciNums[i-2];
            System.out.println(fibonacciNums[i]);
        }


         */
    }
}

表示だけならArrayListは使いません。

for(int i = 0; i < x; i++){
    System.out.println(fibonacciNum);
    fibonacciNum = oldNum1 + oldNum2;
    oldNum1 = oldNum2;
    oldNum2 = fibonacciNum;
}

longで表現できるフィボナッチ数は92番目まで、
※long 最大値 9223372036854775807 (約922京)
93番目以降を表現するにはBigIntegerを使えばいけるのかな

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away