Skip to main content
2 of 5
added 205 characters in body
Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k

I'm really surprised if this question isn't a duplicate, but since I failed to find one that asked about the Fibonacci sequence rather than someone using it as an example, I'll answer.

The most natural approach, besides using the built-in Fibonacci function, recursion:

f[0] = 0; f[1] = 1;
f[n_] := f[n] = f[n - 1] + f[n - 2]  (* note memoization *)

Array[f, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Better performing may be Fold and FoldList:

fibonacciList[n_] := Module[{x = 1}, Rest @ NestList[x + (x = #) &, 0, n]]

fibonacciList[10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Another useful way uses LinearRecurrence:

LinearRecurrence[{1, 1}, {1, 1}, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Hopefully these examples inspire you.

Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k