diff --git a/src/algorithms/math/tribonacci/tribonacci.js b/src/algorithms/math/tribonacci/tribonacci.js new file mode 100644 index 00000000..d35481c0 --- /dev/null +++ b/src/algorithms/math/tribonacci/tribonacci.js @@ -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; +} + \ No newline at end of file diff --git a/src/algorithms/math/tribonacci/tribonaciiNth.js b/src/algorithms/math/tribonacci/tribonaciiNth.js new file mode 100644 index 00000000..efeb5847 --- /dev/null +++ b/src/algorithms/math/tribonacci/tribonaciiNth.js @@ -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]; +} + \ No newline at end of file