Languages
[Edit]
EN

JavaScript - Fibonacci sequence / number

15 points
Created by:
chelsea
776

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

// ONLINE-RUNNER:browser;

function calculateValue(number) {
  	if(number < 1) {
    	return 0;
    }
    var a = 0;
    var b = 1;
    for (var i = 1; i < number; ++i) {
		var c = a + b;
      	a = b;
      	b = c;
    }
    return b;
}


// Usage example:

for (var n = 0; n < 10; ++n) {
    var value = calculateValue(n);
    console.log('f(' + n + ')=' + value);
}

2. Recursive algorithm example

// ONLINE-RUNNER:browser;

function calculateValue(number) {
    if(number < 1) return 0;
    if(number < 2) return 1;
    return calculateValue(number - 2) + calculateValue(number - 1);
}


// Usage example:

for (var n = 0; n < 10; ++n) {
    var value = calculateValue(n);
    console.log('f(' + n + ')=' + value);
}

3. Binet's formula example

// ONLINE-RUNNER:browser;

function calculateValue(number) {
    var a = Math.pow(1 + 2.23606797749979, number);
    var b = Math.pow(1 - 2.23606797749979, number);
    var c = 2.23606797749979 * Math.pow(2, number);
    return Math.round((a - b) / c);
}


// Usage example:

for (var n = 0; n < 10; ++n) {
    var value = calculateValue(n);
    console.log('f(' + n + ')=' + value);
}

 

See also

  1. TypeScript - 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.

JavaScript - math (popular problems)

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