New to Mathematica, I am trying to print the out the first 50 Fibonacci numbers using a Do loop, but can't seem to make it work. I know there is a built-in function that returns the Fibonacci sequence given a number but I want to implement it using a Do loop. Any help would greatly appreciate it.
-
you actually want `Table` or `Nest`, but really you need to show the code you are having trouble with. – agentp Feb 07 '17 at 01:01
-
1http://mathematica.stackexchange.com/q/31593/18476 – Karsten7 Feb 07 '17 at 22:16
3 Answers
Something like this
a = 0; b = 1; terms = {a, b};
Do[
{a, b} = {b, a + b};
terms = {terms, b},
{50 - 2}
];
Flatten@terms
I'm sure there are fancier ways.

- 1,041
- 1
- 16
- 24
From An Introduction to Programming with Mathematica, page 178.
Chapter 7. Recursion
F[1] = 1;
F[2] = 1;
F[n_] := F[n - 2] + F[n - 1] /; n > 2
"As it turns out, the condition /; n > 2
is unnecessary because Mathematica looks up specific rules such as F[1] = 1
before more general rules like that for F[n]
. Here is a table of the first ten Fibonacci numbers."
Table[F[i], {i, 1, 10}]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
However, for adequate speed also use memoization:
F[1] = 1;
F[2] = 1;
F[n_] := F[n] = F[n - 2] + F[n - 1]
Table[F[i], {i, 1, 50}]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025}

- 8,443
- 2
- 23
- 40
using Nest
Nest[ Append[#, Total@#[[-2 ;;]]] & , {1, 1}, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}
using Table
Module[{last = 1, lastp = 1, next}, Join[{lastp, last},
Table[next = last + lastp ; lastp = last ; last = next , {10}] ]]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}
Do
with Reap/Sow
:
Reap[Module[{last = 1, lastp = 1 }, Sow[lastp]; Sow[last];
Do[ {lastp, last} = {last, Sow[last + lastp]} ; , {10}] ]][[2, 1]]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}

- 6,849
- 2
- 19
- 37