Fibonacci sequences of higher order : The Nibonacci Sequence
So today I was messing around with optimising the calculation of Fibonacci sequences. Everyone has written code like this
Just a quickie today :)
Yours sincerely, Joey Tribonacci
Quickly we run into performance issues because many of the calculations are redundant, and these redundant repeated duplicate calculations result in massive function stacks. So the obvious solution here is to cache the intermediate results. We can do something like this
I wanted to create a Fibonacci sequence of order N (Or Nibonacci sequence) using these same principles. First we need a cache that will store the N previous Nibonacci numbers. I designed this data structure, and I think it fits the bill:
Glorious right? This is essentially a circular buffer, and it will work as expected in the previous example when substituted appropriately. We could have used a std::vector, but we would then have to defer the generation of our cache to runtime and, more importantly, we would be storing unnecessary results (our memory requirements would increase with the size of the Nibonacci number, instead of the order N). Now let us consider using this to find the Tribonacci numbers:
We can wrap the latest_cache data structure inside a class and obtain something like
We can use it as follows to get Fibonacci, Tribonacci and Decibonacci sequencesJust a quickie today :)
Yours sincerely, Joey Tribonacci
Comments
Post a Comment