From df075adb7dfb9e0e60d9b1992820d65dead22a5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filipe=20Falc=C3=A3o?= Date: Fri, 15 May 2015 22:39:11 -0300 Subject: [PATCH] Fibonacci algorithm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An algorithm to find the nth number in fibonacci’s sequence --- src/others/fibonacci.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/others/fibonacci.js diff --git a/src/others/fibonacci.js b/src/others/fibonacci.js new file mode 100644 index 00000000..6ce98d06 --- /dev/null +++ b/src/others/fibonacci.js @@ -0,0 +1,37 @@ +/** + * Nth number of fibonacci's sequence + * + * Returns the nth number of fibonacci's sequence. + * + * @public + * + * @example + * var fibonacci = require('path-to-algorithms/src/others/fibonacci').fibonacci; + * var nth = fibonacci(20); + * + * console.log(nth); // 6765 + * + * @param {Number} n The nth position in fibonacci's sequence + * + * @module others/fibonacci +*/ +(function (exports) { + 'use strict'; + + function fibonacci (n) { + var n1 = 0; + var n2 = 1; + var aux; + + while (n > 0) { + aux = n1; + n1 = n2; + n2 += aux; + n = n - 1; + } + + return n1; + } + + exports.fibonacci = fibonacci; +})(typeof window === 'undefined' ? module.exports : window);