Javaでフィボナッチ数列を生成:for文、while文、再帰の実装例
Javaにおけるフィボナッチ数列とは
フィボナッチ数列とは、各数が直前の2つの数の和となる数列です。Javaでは通常、0と1から始まります:
0, 1, 1, 2, 3, 5, 8, 13, 21, …
数学的な興味深さだけでなく、フィボナッチ数列はアルゴリズム解析で頻繁に用いられます。例えば、再帰手順の実行時間見積もりや、最大公約数の計算などです。
- for文による実装
- while文による実装
- 再帰による実装
- ユーザー入力による実装
for文を使ったフィボナッチ数列
// for文を使用
public class FibonacciExample {
public static void main(String[] args) {
int maxNumber = 10; // 項数
int previous = 0;
int current = 1;
System.out.print("フィボナッチ数列 " + maxNumber + " 項: ");
for (int i = 1; i <= maxNumber; i++) {
System.out.print(previous + " ");
int next = previous + current;
previous = current;
current = next;
}
}
}
出力:
フィボナッチ数列 10 項: 0 1 1 2 3 5 8 13 21 34
ロジック:
previous = 0、current = 1で初期化maxNumber回ループし、previousを出力して値を更新
while文を使ったフィボナッチ数列
// while文を使用
public class FibonacciWhileExample {
public static void main(String[] args) {
int maxNumber = 10;
int previous = 0;
int current = 1;
System.out.print("フィボナッチ数列 " + maxNumber + " 項: ");
int i = 1;
while (i <= maxNumber) {
System.out.print(previous + " ");
int next = previous + current;
previous = current;
current = next;
i++;
}
}
}
出力:
フィボナッチ数列 10 項: 0 1 1 2 3 5 8 13 21 34
ユーザー入力に基づくフィボナッチ数列
import java.util.Scanner;
public class FibonacciUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("項数を入力してください: ");
int maxNumber = scanner.nextInt();
int previous = 0;
int current = 1;
System.out.print("フィボナッチ数列 " + maxNumber + " 項: ");
for (int i = 1; i <= maxNumber; i++) {
System.out.print(previous + " ");
int next = previous + current;
previous = current;
current = next;
}
scanner.close();
}
}
ロジック: 同じ反復ロジックですが、項数をユーザーから入力で受け取ります。
再帰を使ったフィボナッチ数列
// 再帰実装
public class FibonacciRecursion {
public static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int maxNumber = 10;
System.out.print("フィボナッチ数列 " + maxNumber + " 項: ");
for (int i = 0; i < maxNumber; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
出力:
フィボナッチ数列 10 項: 0 1 1 2 3 5 8 13 21 34
再帰の説明:
- 基本ケース:
n == 0なら0、n == 1 || n == 2なら1を返す - 再帰ケース:
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) - 各呼び出しが2つのサブ呼び出しに分岐し、古典的な定義を反映
再帰は数学的に綺麗ですが、大きなnでは指数時間がかかります。パフォーマンスが重要な場合はメモ化や反復法を使用してください。
Java