EN
TypeScript - Fibonacci sequence / number
3
points
Fibonacci numbers can be computed in three ways:
- with an iterative algorithm,
- with a recursive algorithm,
- with Binet's formula.
Note: presented implementations calculate Fibonacci numbers from 0.
1. Iterative algorithm example
const calculateValue = (number: number): number => {
if (number < 1) {
return 0;
}
let a = 0;
let b = 1;
for (let i = 1; i < number; ++i) {
const c = a + b;
a = b;
b = c;
}
return b;
};
// Usage example:
for (let n = 0; n < 10; ++n) {
const value = calculateValue(n);
console.log('f(' + n + ')=' + value);
}
Output:
f(0)=0
f(1)=1
f(2)=1
f(3)=2
f(4)=3
f(5)=5
f(6)=8
f(7)=13
f(8)=21
f(9)=34
2. Recursive algorithm example
const calculateValue = (input: number): number => {
if (input < 1) return 0;
if (input < 2) return 1;
return calculateValue(input - 2) + calculateValue(input - 1);
};
// Usage example:
for (let n = 0; n < 10; ++n) {
const value = calculateValue(n);
console.log('f(' + n + ')=' + value);
}
Output:
f(0)=0
f(1)=1
f(2)=1
f(3)=2
f(4)=3
f(5)=5
f(6)=8
f(7)=13
f(8)=21
f(9)=34
3. Binet's formula example
const calculateValue = (input: number): number => {
const a = Math.pow(1 + 2.23606797749979, input);
const b = Math.pow(1 - 2.23606797749979, input);
const c = 2.23606797749979 * Math.pow(2, input);
return Math.round((a - b) / c);
};
// Usage example:
for (let n = 0; n < 10; ++n) {
const value = calculateValue(n);
console.log('f(' + n + ')=' + value);
}
Output:
f(0)=0
f(1)=1
f(2)=1
f(3)=2
f(4)=3
f(5)=5
f(6)=8
f(7)=13
f(8)=21
f(9)=34