If you are a bit serious about coding, or maybe you read the Da Vinci code, then you might know about the Fibonacci sequence. In this sequence every next number is the sum of the two previous numbers. The Fibonacci sequence begins with 0, 1, 1, 2, 3, 5, 8, 13, 21 etc.
We can extrapolate this to make our own Fibonacci sequences. Something like a Tribonacci sequence which takes the sum of the previous three numbers to come up with the next number. It would look something like 0, 0, 1, 1, 2, 4, 7, 13 etc.
If we continue on this path then we would continue into Tetranacci and so forth so we could better make a function to create a N-Fibonacci. Something which creates a Fibonacci sequence which takes the previous n terms to come up with the next number.
Being the author of this blog and all let me kick it off with an example in Python.
#!/usr/bin/env python
def n_fib(n, m):
c = [0] * (n-1) + [1]
for i in xrange(len(c), m):
c.append(sum(c[i-n:i]))
return c
I am interested in implementations in other languages. Maybe some functional examples. Maybe some PHP, Perl or even Brainfuck?
Wait before you post. Wordpress’s comments system clearly is sucky when pasting code. It removes < and > and such so maybe it’s better to pastebin your code and post the link in the comments. Use a pastebin like dpaste.