mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 07:29:47 +08:00

* docs: update js doc * feat: add number type validation condition * pref: Optimize space complexity remove the Array from the algo and used two flag varible to calculate last two numbers & optimize the sapce complexity O(n) to O(1) * test: add test case for invalid types
28 lines
698 B
JavaScript
28 lines
698 B
JavaScript
/**
|
|
* @function fibonacci
|
|
* @description Fibonacci is the sum of previous two fibonacci numbers.
|
|
* @param {Integer} N - The input integer
|
|
* @return {Integer} fibonacci of N.
|
|
* @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
|
|
*/
|
|
const fibonacci = (N) => {
|
|
if (!Number.isInteger(N)) {
|
|
throw new TypeError('Input should be integer')
|
|
}
|
|
|
|
// memoize the last two numbers
|
|
let firstNumber = 0
|
|
let secondNumber = 1
|
|
|
|
for (let i = 1; i < N; i++) {
|
|
const sumOfNumbers = firstNumber + secondNumber
|
|
// update last two numbers
|
|
firstNumber = secondNumber
|
|
secondNumber = sumOfNumbers
|
|
}
|
|
|
|
return N ? secondNumber : firstNumber
|
|
}
|
|
|
|
export { fibonacci }
|