Fibonacci numbers grow approximately exponentially. The 1,000,000th Fibonacci number is huge, it has 208,988 decimal digits. It also takes a fair amount of memory to store:
ByteCount@Fibonacci[1000000]
(* 86856 *)
This is 86 kB. Does Mathematica store huge numbers efficiently? How many bits/bytes do we need at minimum for this number? Let's calculate it:
Length@IntegerDigits[Fibonacci[1000000], 2]/8.
(* 86780.1 *)
So it seems Mathematica's internal storage is in fact very efficient.
Now how much memory would the first million Fibonacci numbers take to store? Considering that Fibonacci numbers grow approximately exponentially, the number of bits needed to store them grows approximately linearly. So a rough estimate for the storage requirements of the list is
ByteCount@Fibonacci[1000000]*1000000/2
(* 43428000000 *)
That's 43 GB (!!). If you don't have ~64 GB of RAM in your computer, it is expected that Mathematica will run out of memory during this calculation.
To sum it up, what you see is not related to your usage of For
loops. In this case one million is really an excessive number unless you have a lot of memory.
I tried your code on a machine with 64 GB of RAM and it finished without problems. The memory monitor showed about 42 GB of memory usage for Mathematica.
Fibonacci
is already built-in to Mathematica, and more generallyRSolve
is able to symbolically evaluate the $n$th term of many types of recursive equations. However, that's probably irrelevant, as your question appears to be more aimed at the memory-management aspects of this type of computation. $\endgroup$ – DumpsterDoofus Nov 30 '14 at 22:24