forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastFibonacciNumber.js
More file actions
Latest commit
25 lines (22 loc) · 767 Bytes
/
Copy pathFastFibonacciNumber.js
File metadata and controls
25 lines (22 loc) · 767 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
/**
* @function fastFibonacci
* @description fastFibonacci is same as fibonacci algorithm by calculating the sum of previous two fibonacci numbers but in O(log(n)).
* @param {Integer} N - The input integer
* @return {Integer} fibonacci of N.
* @see [Fast_Fibonacci_Numbers](https://www.geeksforgeeks.org/fast-doubling-method-to-find-the-nth-fibonacci-number/)
*/
// recursive function that returns (F(n), F(n-1))
constfib=(N)=>{
if(N===0)return[0,1]
const[a,b]=fib(Math.trunc(N/2))
constc=a*(b*2-a)
constd=a*a+b*b
returnN%2 ? [d,c+d] : [c,d]
}
constfastFibonacci=(N)=>{
if(!Number.isInteger(N)){
thrownewTypeError('Input should be integer')
}
returnfib(N)[0]
}
export{fastFibonacci}