LoginSignup
0
1

More than 3 years have passed since last update.

フィボナッチ数列の初歩メモ

Posted at



・フィボナッチ数列

フィボナッチ数列は、イタリアの数学者レオナルド・フィボナッチが考えた「ウサギ算」から導かれる数列です。この数列は、自然界の現象に数多く出現し、ヒマワリの種の配列にもフィボナッチ数列の法則が働いているといわれている。

n番目のフィボナッチ数をFnで表すと、Fnは再帰的に

F0 = 0
F1 = 1

Fn+2 = Fn + Fn+1 (n0)

で定義される。



1番目と2番目の値を足すと3番目の値になる。
言い方を変えると、ひとつ前とふたつ前の値を足した数が次の数となる。

・実際に書いたコード

public class TryJava0120 {

    public static void main(String[] args) {

        int f0, f1, fn;

        f0 = 0;
        System.out.println("f0= " + f0);

        f1 = 1;
        System.out.println("f1= " + f1);

        for (int i = 2; i <= 20; i++) {
            fn = f0 + f1;

            System.out.println(fn);
            f0 = f1;
            f1 = fn;

            System.out.println(f0 + " + " + f1 + "は");
        }

    }

}



・実行結果

f0= 0
f1= 1
1
1 + 1
2
1 + 2
3
2 + 3
5
3 + 5
8
5 + 8
13
8 + 13
21
13 + 21
34
21 + 34
55
34 + 55
89
55 + 89
144
89 + 144
233
144 + 233
377
233 + 377
610
377 + 610
987
610 + 987
1597
987 + 1597
2584
1597 + 2584
4181
2584 + 4181
6765
4181 + 6765

前々回の計算結果(f0) + 前回の計算結果(f1)のイコールとして、変数fnに値が代入され出力される。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1