Skip to content

Instantly share code, notes, and snippets.

@vpodk
Last active May 30, 2019 19:00
Show Gist options
  • Save vpodk/8c21ee34f2f8cd3a11f7dad6a6e94d90 to your computer and use it in GitHub Desktop.
Save vpodk/8c21ee34f2f8cd3a11f7dad6a6e94d90 to your computer and use it in GitHub Desktop.
Calculating the value of the Fibonacci number.
/**
* +------------------------------------+
* | FIBONACCI TABLE |
* +------------------------------------+
* | n 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
* | xn 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 |
* +------------------------------------+
*
* @see https://en.wikipedia.org/wiki/Big_O_notation
* @see https://en.wikipedia.org/wiki/Fibonacci_number#Sequence_properties
*/
/**
* Calculates the value of the Fibonacci number using iterative solution.
* @return {number} Returns the value of the Fibonacci number.
* @see https://en.wikipedia.org/wiki/Fibonacci_number#Sequence_properties
*/
function fibonacci(n) {
var list = [0, 1];
for (var i = 2; i < n + 1; ++i) {
// TODO: Add validation for `Number.MAX_SAFE_INTEGER`.
list[i] = list[i - 1] + list[i - 2];
}
return list[n];
}
/**
* Calculates the value of the Fibonacci number using recursive solution.
* @return {number} Returns the value of the Fibonacci number.
* @see https://en.wikipedia.org/wiki/Fibonacci_number#Sequence_properties
*/
function fibonacci(n) {
// TODO: Add validation for `Number.MAX_SAFE_INTEGER`.
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
/**
* Calculates the value of the Fibonacci number using Golden ration.
* @return {number} Returns the value of the Fibonacci number.
* @see https://en.wikipedia.org/wiki/Fibonacci_number#Sequence_properties
* @see https://en.wikipedia.org/wiki/Golden_ratio
*
* The golden ration `phi ^ n / sqrt(5)` is asymptotic to the fibonacci of n.
* Rounding that value up, indeed get the fibonacci value.
*/
function fibonacci(n) {
if (n > 1) {
var phi = (1 + Math.sqrt(5)) / 2; // 1.6180339887...
// `Math.pow` returns` Infinity` if the result is greater than `Number.MAX_VALUE`.
var asymp = Math.pow(phi, n) / Math.sqrt(5);
return Math.round(asymp);
}
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment