Skip to content

Commit 7a552de

Browse files
committed
Create: 1137-n-th-tribonacci-number
1 parent ee7a3bc commit 7a552de

File tree

4 files changed

+80
-0
lines changed

4 files changed

+80
-0
lines changed

go/1137-n-th-tribonacci-number.go

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package main
2+
3+
func main() {
4+
5+
}
6+
7+
func tribonacci(n int) int {
8+
t := [3]int{0, 1, 1}
9+
10+
if n < 3 {
11+
return t[n]
12+
}
13+
14+
for i := 3; i < n+1; i++ {
15+
t[0], t[1], t[2] = t[1], t[2], sum(t)
16+
}
17+
18+
return t[2]
19+
}
20+
21+
func sum(arr [3]int) int {
22+
total := 0
23+
24+
for _, val := range arr {
25+
total += val
26+
}
27+
28+
return total
29+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
var tribonacci = function (n) {
6+
let t = [0, 1, 1];
7+
8+
if (n < 3) return t[n];
9+
10+
for (let i = 3; i < n + 1; i++) {
11+
[t[0], t[1], t[2]] = [t[1], t[2], sum(t)];
12+
}
13+
14+
return t[2];
15+
};
16+
17+
function sum(arr) {
18+
return arr.reduce((a, b) => a + b);
19+
}

rust/1137-n-th-tribonacci-number.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
impl Solution {
2+
pub fn tribonacci(n: i32) -> i32 {
3+
let mut t = [0, 1, 1];
4+
5+
if n <= 2 {
6+
return t[n as usize];
7+
}
8+
9+
for i in 3..(n + 1) as usize {
10+
t.swap(0, 1);
11+
t.swap(1, 2);
12+
t[2] = t.iter().sum();
13+
}
14+
15+
t[2]
16+
}
17+
}
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function tribonacci(n: number): number {
2+
let t = [0, 1, 1];
3+
4+
if (n < 3) return t[n];
5+
6+
for (let i = 3; i < n + 1; i++) {
7+
[t[0], t[1], t[2]] = [t[1], t[2], sum(t)];
8+
}
9+
10+
return t[2];
11+
}
12+
13+
function sum(arr: number[]): number {
14+
return arr.reduce((a, b) => a + b);
15+
}

0 commit comments

Comments
 (0)