## Tribonacci Numbers

### September 14, 2012

We use `iterate`

from the Standard Prelude to calculate the tribonacci sequence:

`(define (tribs n)`

(iterate n + 1 1 2))

Thus, the first 25 elements of the tribonacci sequence are:

`> (tribs 25)`

(1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609

19513 35890 66012 121415 223317 410744 755476 1389537)

We use the matrix datatype from the Standard Prelude, matrix multiplication from the exercise on matrices and matrix powering from the exercise on fibonacci numbers to define this calculation of the *n*th tribonacci number:

`(define (trib n)`

(matrix-ref

(matrix-power

#( #(1 1 0)

#(1 0 1)

#(1 0 0))

n) 2 0))

Here’s an example (that’s all one big number):

`> (trib 1000)`

149995252232719672994127119633436824577569749158277812578756625414

806969052829656874238599632454281061578352939019541212503423640707

076075654939096072721522668597272334783989205780788704954034154039

4345570010550821354375819311674972209464069786275283520364029575324

Finally, we calculate the tribonacci constant as the ratio between two successive tribonacci numbers:

`> (inexact->exact (/ (trib 1000) (trib 999)))`

1.8392867552141612

You can run the program at http://programmingpraxis.codepad.org/mxq30iLw.

A python version that uses the numpy library for matrices

Another Python version with the power of a matrix explicitly in the code.

Calculation of the limit of the ratio as one of the roots the characteristic polynomial.

This is also the real eigenvalue of the powering matrix.

It’s been a while since I’ve used GNU Octave (Matlab clone), so I thought I’d give it a try. Not particularly clever, but it was good practice to brush up on working with matrices.

My implementation in Common lisp

As I mentioned in a recent comment on the fibonacci post, it’s actually impossible to achieve O(log n) performance for arbitrarily large n. The sequence is (to a close approximation) exponential, so the lengths of the binary or decimal values increase linearly. It is thus impossible for any algorithm to run in sublinear time.

Another Python solution:

#include

using namespace std;

int main()

{

unsigned long int Counter;

unsigned long int result = 0;

unsigned long int numa, numb, numc;

numa = 0;

numb = 0;

numc = 1;

unsigned long int number;

cout << "Qual o numero que desejas conhecer da sequencia tribonacci?" << endl <> number;

cout << endl << endl;

for(Counter = 0; Counter < number – 1; Counter++)

{

result = numa + numb + numc;

numa = numb;

numb = numc;

numc = result;

}

cout << "O Valor Tribonacci do numero " << number << " e igual a: " << result;

return 0;

}