mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-13 06:23:00 +08:00
Tribonacci sequence
This commit is contained in:
parent
dc1047df72
commit
44b1758631
22
src/algorithms/math/tribonacci/tribonacci.js
Normal file
22
src/algorithms/math/tribonacci/tribonacci.js
Normal 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;
|
||||||
|
}
|
||||||
|
|
18
src/algorithms/math/tribonacci/tribonaciiNth.js
Normal file
18
src/algorithms/math/tribonacci/tribonaciiNth.js
Normal 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];
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user