Languages
[Edit]
EN

TypeScript - Fibonacci sequence / number

3 points
Created by:
Welsh
772

Fibonacci numbers can be computed in three ways:

  1. with an iterative algorithm,
  2. with a recursive algorithm,
  3. 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

 

See also

  1. JavaScript - Fibonacci sequence / number

References

  1. Binet's Fibonacci number formula - Wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join