Here's an optimal Fibonacci function in TypeScript with multiple implementations for different use cases:
// Iterative approach - O(n) time, O(1) space
// Best for most use cases
function fibonacci(n: number): number {
if (n <= 1) return n;
let prev = 0;
let curr = 1;
for (let i = 2; i <= n; i++) {
const temp = curr;
curr = prev + curr;
prev = temp;
}
return curr;
}
// Memoized recursive approach - O(n) time, O(n) space
// Good for repeated calls with different values
function fibonacciMemo(): (n: number) => number {
const cache = new Map<number, number>();
return function fib(n: number): number {
if (n <= 1) return n;
if (cache.has(n)) {
return cache.get(n)!;
}
const result = fib(n - 1) + fib(n - 2);
cache.set(n, result);
return result;
};
}
// Generator function - memory efficient for sequences
function* fibonacciGenerator(): Generator<number> {
let prev = 0;
let curr = 1;
yield prev;
yield curr;
while (true) {
const next = prev + curr;
yield next;
prev = curr;
curr = next;
}
}
// Matrix exponentiation - O(log n) time
// Fastest for very large n
function fibonacciMatrix(n: number): number {
if (n <= 1) return n;
const multiply = (a: number[][], b: number[][]): number[][] => {
return [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
[a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]]
];
};
const power = (mat: number[][], n: number): number[][] => {
if (n === 1) return mat;
if (n % 2 === 0) {
const half = power(mat, n / 2);
return multiply(half, half);
}
return multiply(mat, power(mat, n - 1));
};
const baseMatrix: number[][] = [[1, 1], [1, 0]];
const result = power(baseMatrix, n);
return result[0][1];
}
// Usage examples:
console.log(fibonacci(10)); // 55
const fibMemo = fibonacciMemo();
console.log(fibMemo(50)); // 12586269025
const gen = fibonacciGenerator();
for (let i = 0; i < 10; i++) {
console.log(gen.next().value);
}
console.log(fibonacciMatrix(100)); // 354224848179262000000
The iterative approach is generally the most optimal for single calculations due to its O(n) time complexity and O(1) space complexity. For very large values of n, the matrix exponentiation method with O(log n) time complexity becomes more efficient, though it's more complex to implement. The memoized version is ideal when you need to calculate multiple Fibonacci numbers repeatedly, and the generator is perfect for producing Fibonacci sequences on demand without storing the entire sequence in memory.