0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【フィボナッチ数列】PHPで再帰・ループ・コントローラ実装を練習してみた。

Last updated at Posted at 2025-05-12

はじめに

この記事では、PHP(Laravel)を使って「フィボナッチ数列」を求める処理を実装してみた内容をまとめます。

①フィボナッチ数列とは?

前の2つの数字を足して次の数字を作る数列のことです。

0,1,1,2,3,5,8,13,21,.....

数式で表すと:

F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2)(n >= 2)

②Laravelでフィボナッチを求める方法

1. ループを求める(最も効率的)

public function loopFibonacci($n)
{
    $fib = [0, 1];

    for ($i = 2; $i <= $n; $i++) {
        $fib[$i] = $fib[$i - 1] + $fib[$i - 2];
    }
    return $fib;
}

2. 再帰で求める(理解しやすい)

public function recursiveFibonacci($n)
{
    if($n < 2){
        return $n;
    }
    return $this->recursiveFibonacci($n - 1) + $this->recursiveFibonacci($n - 2);
}

*再帰は計算量が多く、10以上になると激重になる!

controllerに組み込む例

php artisan make:controller FibonacciContoroller
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FibonacciContoroller extends Contoroller
{
    public function index()
    {
        $fib = $this->loopFibonacci(10);
        return view('fibonacci.index', compact('fib'));
    }
    private function loopFibonacci($n)
    {
        $fib = [0, 1];
        for ($i = 2; $i <= $n; $i++) {
            $fib[$i] = $fib[$i - 1] +  $fib[$i - 2];
        }
        return $fib;
    }
}

Bladeファイルでの表示

<!-- resources/views/fibonacci/index.blade.php -->
<h1>フィボナッチ数列</h1>
<ul>
    @foreach ($fib as $index => $value)
        <li>F{{ $index }} = {{ $value }}</li>
    @endforeach
</ul>

③まとめ

  • フィボナッチ数列はロジック練習に最適な題材
  • Laravelではコントローラ → ロジック → Bladeと流れをつかみやすい
  • 再帰とループ、どちらも書いて比較してみると理解が深まる!
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?