AlgoTales · Roadmap

Fibonacci

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Fibonacci numbers start 0, 1 and then each is the sum of the two before it. The slow way of calculating them repeats huge amounts of work, which makes it the classic demonstration of why saving answers matters. Any code where a result depends on the last couple of results behaves the same way.

Practical use cases

  • Web app: The page that froze on a recursive function. A developer wrote a function that calls itself twice to compute the 40th term of a sequence, and the browser tab froze for several seconds. It was recalculating the same small values hundreds of millions of times. Keeping the last two values in a loop made it instant.
  • Web app: Compound growth and referral levels. A referral program page shows how many people are in each level when each level has as many people as the two levels before it added together. A simple loop keeps two numbers and gives the table for 30 levels without delay. Marketing can then change the number of levels in a form field and see the table update instantly, without the page ever hanging on larger values.
  • System: Nature patterns and algorithm courses. The same growth pattern appears in plant spirals and in the way rabbit populations were first modelled. It is also the standard first example in algorithm courses. In each of these, the rule of adding the previous two is easy, and the only real lesson is to remember earlier answers instead of recomputing them.

The story: Grandpa's Money Plant

Grandpa Bhaskar has a money plant on his balcony that he adores. He explained its habit to Mira: "A new shoot is too young to do anything for one month. After that it becomes a grown-up and gives one new shoot every month." Mira wrote the count of shoots for each month: 0, 1, 1, 2, 3, 5, 8... and her eyes went wide. "Grandpa, each number is the two before it added together!"

Then Kabir asked a bold question: "How many shoots in month 40?" Mira's first idea was to ask the same question as a recursion: "month 40 needs month 39 and month 38". That seemed neat, but when Kabir actually tried it, the same months were asked about again and again. Month 30 was being worked out over a million times. His laptop fan roared.

Grandpa smiled: "Why not walk forward instead? Write month 0, month 1, then month 2 from them, then month 3, and so on. You only need to remember the last two numbers." One short loop, two variables, month 40 in a blink.

This famous list is the Fibonacci sequence, and it is the smallest honest example of dynamic programming. It shows both sides of the lesson: the slow, repeating recursion, and the quick DP that remembers.

How to spot this problem, and where you need it

A calculation where each value depends on the one or two before it runs painfully slowly when written as a function calling itself.

Signs you need it

  • A recursive function calls itself two or more times and the running time explodes when the input goes from 30 to 40.
  • Adding one to the input roughly doubles the time taken.
  • The recurrence is like "today = yesterday + day before", as in growth, counts or levels.

Where to use it in a project

  • Any sequence or level-by-level count in reports, referral trees or growth projections.
  • Replacing a naive recursive helper that is slowing down a page or an API response.

The solution

Start with the two base values. In a loop from 2 up to n, compute the next value as the sum of the previous two, then slide the two stored values forward. At the end, the latest value is your answer. Nothing is recalculated, and only two numbers are held in memory. The alternative is to keep the recursion but store each answer the first time it is found (memoization).

Payoff: Before: over a billion calls for the 45th term and a frozen tab. After: 45 simple additions, instantly.

Explain it like I am 8

You make a chain of numbers where each new number is the two numbers just before it, added. 0, 1, then 1, 2, 3, 5, 8... You never have to look further back than the last two, so you can carry on forever just by holding two numbers in your hands.

How it works, step by step

  1. State: fib[i] is the i-th Fibonacci number.
  2. Base cases: fib[0] = 0 and fib[1] = 1.
  3. Transition: fib[i] = fib[i-1] + fib[i-2].
  4. Fill from small to big with a loop (tabulation). Plain recursion would recompute the same values many times.
  5. Shrink the memory: only the last two values matter, so two variables are enough.

The code in four languages

PHP

<?php
// Fibonacci with the DP idea: build forward and remember only the last two.
function fib(int $n): int {
    if ($n < 2) return $n;                       // base cases: fib(0)=0, fib(1)=1
    $prev = 0;                                   // fib(i-2)
    $curr = 1;                                   // fib(i-1)
    for ($i = 2; $i <= $n; $i++) {
        [$prev, $curr] = [$curr, $prev + $curr]; // slide forward
    }
    return $curr;
}

$first = [];
for ($i = 0; $i <= 11; $i++) $first[] = fib($i);
echo implode(" ", $first), "\n";                // 0 1 1 2 3 5 8 13 21 34 55 89
echo "fib(50) = ", fib(50), "\n";               // 12586269025 (plain recursion would take hours)

JavaScript

// Fibonacci with the DP idea: build forward and remember only the last two.
function fib(n) {
  if (n < 2) return n;                           // base cases: fib(0)=0, fib(1)=1
  let prev = 0;                                  // fib(i-2)
  let curr = 1;                                  // fib(i-1)
  for (let i = 2; i <= n; i++) {
    [prev, curr] = [curr, prev + curr];          // slide forward
  }
  return curr;
}

const first = [];
for (let i = 0; i <= 11; i++) first.push(fib(i));
console.log(first.join(" "));                    // 0 1 1 2 3 5 8 13 21 34 55 89
console.log("fib(50) =", fib(50));               // 12586269025 (plain recursion would take hours)

Java

import java.util.*;

public class Main {
    // Fibonacci with the DP idea: build forward and remember only the last two.
    static long fib(int n) {
        if (n < 2) return n;                         // base cases: fib(0)=0, fib(1)=1
        long prev = 0;                               // fib(i-2)
        long curr = 1;                               // fib(i-1)
        for (int i = 2; i <= n; i++) {
            long next = prev + curr;                 // slide forward
            prev = curr;
            curr = next;
        }
        return curr;
    }

    public static void main(String[] args) {
        StringJoiner first = new StringJoiner(" ");
        for (int i = 0; i <= 11; i++) first.add(String.valueOf(fib(i)));
        System.out.println(first);                   // 0 1 1 2 3 5 8 13 21 34 55 89
        System.out.println("fib(50) = " + fib(50));  // 12586269025 (plain recursion would take hours)
    }
}

Go

package main

import "fmt"

// Fibonacci with the DP idea: build forward and remember only the last two.
func fib(n int) int {
	if n < 2 {
		return n // base cases: fib(0)=0, fib(1)=1
	}
	prev := 0 // fib(i-2)
	curr := 1 // fib(i-1)
	for i := 2; i <= n; i++ {
		prev, curr = curr, prev+curr // slide forward
	}
	return curr
}

func main() {
	var first []int
	for i := 0; i <= 11; i++ {
		first = append(first, fib(i))
	}
	fmt.Println(first)                // [0 1 1 2 3 5 8 13 21 34 55 89]
	fmt.Println("fib(50) =", fib(50)) // 12586269025 (plain recursion would take hours)
}

Time: O(n) · Extra space: O(1). One pass with two variables. Plain recursion without a notebook takes exponential time because it repeats itself.

Watch out for

  • Plain recursion fib(n-1) + fib(n-2) with no cache: it repeats the same calls so much that n = 45 can take seconds.
  • Off-by-one in the starting values (starting from 1, 1 instead of 0, 1) shifts every answer.
  • Forgetting that big values overflow in some languages (a 32-bit int overflows near fib(47)).

Quick check

  1. How is each Fibonacci number built?
    • The previous number doubled
    • The sum of the two numbers before it
    • The difference of the last two
  2. Why is plain recursion for fib(40) so slow?
    • It repeats the same sub-problems enormously many times
    • PHP is slow
    • Because 40 is even
  3. What is fib(7) if the list starts 0, 1, 1, 2, 3, 5, 8?
    • 8
    • 13
    • 5