-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathFibonacciNumber.js
More file actions
29 lines (24 loc) · 723 Bytes
/
FibonacciNumber.js
File metadata and controls
29 lines (24 loc) · 723 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
28
29
/**
* @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 an integer')
}
if (N < 0) {
throw new RangeError('Input should be a non-negative integer')
}
let firstNumber = 0
let secondNumber = 1
for (let i = 1; i < N; i++) {
const sumOfNumbers = firstNumber + secondNumber
firstNumber = secondNumber
secondNumber = sumOfNumbers
}
return N ? secondNumber : firstNumber
}
export { fibonacci }