Visualize

Pattern visualizer

Fibonacci Series Up to N

Only the last two terms matter. Each new term is their sum, so the whole sequence can be walked with a pair of variables that shift right one place at a time. The twist compared with 'find the nth Fibonacci number' is the stopping rule: the loop is bounded by the VALUE of the next term against n, not by a count, so it computes one term too many on purpose and discards it. Because Fibonacci numbers only increase, the first term that overshoots n proves every later one does too — no need to look further. Animated on: n = 30 — print every Fibonacci number that is at most 30, starting from 0 and 1..

Rolling pair of terms, bounded by value rather than by count

time O(log n) termsspace O(1) beyond the outputstep 1 / 10
0
[0]
1
[1]
line 4

The two seeds 0 and 1 are given, not computed — every later term needs two predecessors to add, so the sequence cannot bootstrap itself. a and b always point at the last two terms; that pair is the entire state this loop carries.

Pseudocode
1FUNCTION fibonacciUpTo(n):
2 IF n < 1
3 RETURN [0]
4 series <- [0, 1]
5 WHILE TRUE
6 next <- series[LENGTH(series) - 1] + series[LENGTH(series) - 2]
7 IF next > n
8 BREAK
9 APPEND next TO series
10 RETURN series

← / → step · space play · Home restart

Where to practice Math