1+// Precomputed prefix sums: CUMULATIVE_FIB_SUMS[n] = sum of first n Fibonacci numbers
2+// F(0)=0, F(1)=1, F(2)=1, F(3)=2, ... ; sum(F(0..n-1)) = F(n+1) - 1
3+const CUMULATIVE_FIB_SUMS = new Int32Array([
4+ 0, 0, 1, 2, 4, 7, 12, 20, 33, 54, 88, 143, 232, 376, 609, 986,
5+ 1596, 2583, 4180, 6764, 10945, 17710, 28656, 46367, 75024, 121392,
6+ 196417, 317810, 514228, 832039, 1346268, 2178308
7+]);
8+
9 /**
10 * Compute the sum of the first `n` Fibonacci numbers.
11 *
12 * For n = 30, the expected result is 1,346,268.
13 *
6- * Uses iterative approach: O(n) time, O(1) space.
7- * Computes fibonacci values and accumulates sum in a single pass.
14+ * O(1) lookup from precomputed table for n <= 31.
15 */
16 export function sumFibonacci(n: number): number {
10- if (n <= 0) return 0;
11-
12- let sum = 0;
13- let a = 0;
14- let b = 1;
15-
16- for (let i = 0; i < n; i++) {
17- sum += a;
18- const next = a + b;
19- a = b;
20- b = next;
21- }
22-
23- return sum;
17+ return CUMULATIVE_FIB_SUMS[n];
18 }