PHP: Fibonacci with memory

A plain recursive Fibonacci is very slow. A static memory makes it fast.

What to build

A program that prints the n-th Fibonacci number.

Requirements

  • Write a recursive function fib(int $n): int with a static array that remembers the results.
  • Read n and print fib(n).

Input

One integer n.

Output

One integer.

Constraints

0 ≤ n ≤ 40.

Example

Input:

10

Output:

55

Why it works

The base cases stop the recursion, and the static cache means every value is computed once instead of millions of times.

Examples

Example 1 · Input
10
Expected output
55
Example 2 · Input
0
Expected output
0

Hints

Hint 1

fib(n) = fib(n - 1) + fib(n - 2), with fib(0) = 0 and fib(1) = 1 as base cases.

Hint 2

Keep a static array inside the function, so each value is calculated only once.

Solution

Show one correct solution (try it yourself first)
<?php
function fib(int $n): int
{
    static $cache = [];
    if ($n < 2) {
        return $n;
    }
    if (!isset($cache[$n])) {
        $cache[$n] = fib($n - 1) + fib($n - 2);
    }
    return $cache[$n];
}

$n = (int) trim(fgets(STDIN));
echo fib($n), "\n";

▶ Open this solution in the compiler

Lesson: Functions →