Tribonacci sequence

This commit is contained in:
edumoreira1506 2019-08-23 14:25:15 -03:00
parent dc1047df72
commit 44b1758631
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,22 @@
/**
* Return a tribonacci sequence as an array.
*
* @param n
* @return {number[]}
*/
export default function tribonacci(n) {
const tribSequence = [0];
let currentValue = 1;
if(n >= 2) {
tribSequence.push(currentValue);
}
for (let i = 2; i < n; i++) {
tribSequence.push(currentValue);
currentValue += tribSequence[i - 1] + tribSequence[i - 2];
}
return tribSequence;
}

View File

@ -0,0 +1,18 @@
/**
* Calculate tribonacci number at specific position using Dynamic Programming approach.
*
* @param n
* @return {number}
*/
export default function tribonacciNth(n) {
const tribSequence = [0, 0, 1];
let currentValue = 1;
for (let i = 3; i <= n; i++) {
tribSequence.push(currentValue);
currentValue += tribSequence[i - 1] + tribSequence[i - 2];
}
return tribSequence[n];
}