rad-experiment show 838bb642568286f42c9c84ea41cbd361a134d5ff
by vagrant · Mar 31 13:59 2026
O(log n) fast doubling fibonacci with sum identity
Delta-0.00%
Metricduration (ms)
Criterialower_is_better
LOC+20-9
Kept Discarded Running best
Measurements
Metric
Baseline
Candidate
Delta
duration (ms)How long the code takes to run. Less is better.
0.000 ms (n=5)
0.000 ms (n=5)
-0.00%
ops_per_sec (ops/sec)Operations completed per second. More is better.
1499245.760 ops/sec
1845018.670 ops/sec
+23.06%
p95 (ms)Measures p95 in ms. Less is better.
0.000 ms
0.000 ms
-0.00%
Diff
~ src/index.ts
@@ -2,22 +2,33 @@
2 * Compute the sum of the first `n` Fibonacci numbers.
3 *
4 * Uses the identity: sum(F(0)..F(n-1)) = F(n+1) - 1
5- * Combined with iterative O(n) fibonacci computation.
5+ * Computes F(n+1) via O(log n) fast doubling:
6+ * F(2k) = F(k) * (2*F(k+1) - F(k))
7+ * F(2k+1) = F(k)^2 + F(k+1)^2
8 *
9 * For n = 30, the expected result is 1,346,268.
10 */
11 export function sumFibonacci(n: number): number {
12 if (n <= 0) return 0;
11- if (n === 1) return 0; // F(0) = 0
13+ if (n === 1) return 0;
1413- // Compute F(n+1) iteratively — sum of first n fibs = F(n+1) - 1
15+ return fastFib(n + 1) - 1;
16+}
17+
18+function fastFib(n: number): number {
19+ if (n <= 0) return 0;
20 let a = 0;
21 let b = 1;
16- for (let i = 2; i <= n + 1; i++) {
17- const next = a + b;
18- a = b;
19- b = next;
22+ for (let bit = 1 << (31 - Math.clz32(n)); bit > 0; bit >>>= 1) {
23+ const d = a * (2 * b - a);
24+ const e = a * a + b * b;
25+ if (n & bit) {
26+ a = e;
27+ b = d + e;
28+ } else {
29+ a = d;
30+ b = e;
31+ }
32 }
21-
22- return b - 1;
33+ return a;
34 }