Ikanobori Weblog

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.

7 COMMENTS
December 13, 2008

Here is a faster, more pythonic version. Use as an iterator.

from collections import deque

def n_fib(n):
cache = deque([0] * (n-1) + [1])
sumc = sum(cache)
while True:
cache.append(sumc)
fib = cache.popleft()
sumc = sumc * 2 – fib
yield fib

While it is not n-fib, this is a good starting point:
http://www.scriptol.org/fibonacci-any-programming-language.html

December 13, 2008

How does one indent?

def n_fib(n):
—-cache = deque([0] * (n-1) + [1])
—-sumc = sum(cache)
—-while True:
——–cache.append(sumc)
——–fib = cache.popleft()
——–sumc = sumc * 2 – fib
——–yield fib

December 13, 2008
December 14, 2008

@Kyle, you probably don’t. I need to write (or find) some plugin for wordpress which allows some code to be posted in comments.

December 15, 2008

Here is an attempt in Clojure. I’m new to Clojure and I suspect there are probably more idiomatic ways of doing it, but hopefully this isn’t too bad:

http://pastie.org/339119

Tetha
June 24, 2009

As promised, here is the horrible copy-minimal C-solution. It was produced in order to check a dataflow-analysis in a compiler, and it did pretty well :) So, don’t bash me for handoptimizing this beyond recognition. (Hope you will collect the pastes in a new post so they don’t get lost) http://paste.pocoo.org/show/124857/

Tetha
June 24, 2009

Ah, I noticed, I grabbed the wrong version, check the reply-paste for less unecessary if’s in the fib/1 (the second if is unreachable)

Post a comment