Easy Recursion

Fibonacci

Receives a non-negative integer n and returns the n-th Fibonacci number, where fib(0) = 0, fib(1) = 1, and every later term is the sum of the two before it (fib(k) = fib(k-1) + fib(k-2)). It computes the answer via top-down recursion: fib(n) calls fib(n-1) and fib(n-2), which in turn call their own smaller sub-problems, down to the base cases 0 and 1. A memo (a map from index to its already-solved value) records every sub-problem's result the first time it is solved, so a later call for the same index returns instantly instead of recomputing it — turning the naive exponential recursion into O(n) time and space. Returns the single integer fib(n); n ≤ 0 returns 0 directly, with no recursion.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References