There is lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.
In math, it's given in a recursive form:
In programming, infinite doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
Try it in your favourite language and see that this form requires a lot of time as n gets bigger. In fact, this is O(2n) in time.
Go on on the sites I linked to you and will see this (on wolfram):
This one is pretty easy to implement and very, very fast to compute, in Python:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
An other way to do it is following the definition (from wikipedia):
The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.
If your language supports iterators you may do something like:
def F():
a,b = 0,1
while True:
yield a
a, b = b, a + b
Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.
Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )
In most languages you can do something like:
def SubFib(startNumber, endNumber):
n = 0
cur = f(n)
while cur <= endNumber:
if startNumber <= cur:
print cur
n += 1
cur = f(n)
In python I'd use the iterator form and go for:
def SubFib(startNumber, endNumber):
for cur in F():
if cur > endNumber: return
if cur >= startNumber:
yield cur
for i in SubFib(10, 200):
print i
My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!
I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a Python Enhancement Proposal), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:
def fib():
a, b = 0, 1
while True: # First iteration:
yield a # yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1)
and usage:
for index, fibonacci_number in zip(range(10), fib()):
print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number))
prints:
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55
(For attribution purposes, I recently noticed a similar implementation in the Python documentation on modules, even using the variables a
and b
, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.)
The Online Encyclopedia of Integer Sequences defines the Fibonacci Sequence recursively as
F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1
Succinctly defining this recursively in Python can be done as follows:
def rec_fib(n):
'''inefficient recursive function as defined, returns Fibonacci number'''
if n > 1:
return rec_fib(n-1) + rec_fib(n-2)
return n
But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following:
for i in range(40):
print(i, rec_fib(i))
It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason):
def mem_fib(n, _cache={}):
'''efficiently memoized recursive function, returns a Fibonacci number'''
if n in _cache:
return _cache[n]
elif n > 1:
return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
return n
You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this:
for i in range(40):
print(i, mem_fib(i))
(It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.)
def mem_fib(n, _cache={}):
'''don't do this'''
if n > 1:
return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
return n
As I have been learning Haskell, I came across this implementation in Haskell:
fib@(0:tfib) = 0:1: zipWith (+) fib tfib
The closest I think I can get to this in Python at the moment is:
from itertools import tee
def fib():
yield 0
yield 1
# tee required, else with two fib()'s algorithm becomes quadratic
f, tf = tee(fib())
next(tf)
for a, b in zip(f, tf):
yield a + b
This demonstrates it:
[f for _, f in zip(range(999), fib())]
It can only go up to the recursion limit, though. Usually, 1000, whereas the Haskell version can go up to the 100s of millions, although it uses all 8 GB of my laptop's memory to do so:
> length $ take 100000000 fib
100000000
A commenter asks:
Question for the Fib() function which is based on iterator: what if you want to get the nth, for instance 10th fib number?
The itertools documentation has a recipe for this:
from itertools import islice
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
and now:
>>> nth(fib(), 10)
55
Why not simply do the following?
x = [1,1]
for i in range(2, 10):
x.append(x[-1] + x[-2])
print(', '.join(str(y) for y in x))
The idea behind the Fibonacci sequence is shown in the following Python code:
def fib(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return fib(n-1) + fib(n-2)
This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:
fib(n-1) + fib(n-2)
Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:
fib(2) = fib(1) + fib(0)
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(2) = 1 + 0
fib(2) = 1
We can calculate fib(3) the same way with the arithmetic shown below:
fib(3) = fib(2) + fib(1)
fib(2) = fib(1) + fib(0)
fib(2) = 1
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(3) = 1 + 1 + 0
The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.
This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!
Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.
Time complexity :
The caching feature reduces the normal way of calculating Fibonacci series from O(2^n) to O(n) by eliminating the repeats in the recursive tree of Fibonacci series :
Code :
import sys
table = [0]*1000
def FastFib(n):
if n<=1:
return n
else:
if(table[n-1]==0):
table[n-1] = FastFib(n-1)
if(table[n-2]==0):
table[n-2] = FastFib(n-2)
table[n] = table[n-1] + table[n-2]
return table[n]
def main():
print('Enter a number : ')
num = int(sys.stdin.readline())
print(FastFib(num))
if __name__=='__main__':
main()
This is quite efficient, using O(log n) basic arithmetic operations.
def fib(n):
return pow(2 << n, n + 1, (4 << 2*n) - (2 << n) - 1) % (2 << n)
This one uses O(1) basic arithmetic operations, but the size of the intermediate results is large and so is not at all efficient.
def fib(n):
return (4 << n*(3+n)) // ((4 << 2*n) - (2 << n) - 1) & ((2 << n) - 1)
This one computes X^n in the polynomial ring Z[X] / (X^2 - X - 1) using exponentiation by squaring. The result of that calculation is the polynomial Fib(n)X + Fib(n-1), from which the nth Fibonacci number can be read.
Again, this uses O(log n) arithmetic operations and is very efficient.
def mul(a, b):
return a[0]*b[1]+a[1]*b[0]+a[0]*b[0], a[0]*b[0]+a[1]*b[1]
def fib(n):
x, r = (1, 0), (0, 1)
while n:
if n & 1: r = mul(r, x)
x = mul(x, x)
n >>= 1
return r[0]
Canonical Python code to print Fibonacci sequence:
a,b=1,1
while True:
print a,
a,b=b,a+b # Could also use b=a+b;a=b-a
For the problem "Print the first Fibonacci number greater than 1000 digits long":
a,b=1,1
i=1
while len(str(a))<=1000:
i=i+1
a,b=b,a+b
print i,len(str(a)),a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With