forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacciNumber.js
More file actions
Latest commit
27 lines (23 loc) · 698 Bytes
/
Copy pathFibonacciNumber.js
File metadata and controls
27 lines (23 loc) · 698 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @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)
*/
constfibonacci=(N)=>{
if(!Number.isInteger(N)){
thrownewTypeError('Input should be integer')
}
// memoize the last two numbers
letfirstNumber=0
letsecondNumber=1
for(leti=1;i<N;i++){
constsumOfNumbers=firstNumber+secondNumber
// update last two numbers
firstNumber=secondNumber
secondNumber=sumOfNumbers
}
returnN ? secondNumber : firstNumber
}
export{fibonacci}