File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @function fastFibonacci
3+ * @description fastFibonacci is same as fibonacci algorithm by calculating the sum of previous two fibonacci numbers but in O(log(n)).
4+ * @param {Integer } N - The input integer
5+ * @return {Integer } fibonacci of N.
6+ * @see [Fast_Fibonacci_Numbers](https://www.geeksforgeeks.org/fast-doubling-method-to-find-the-nth-fibonacci-number/)
7+ */
8+
9+ // recursive function that returns (F(n), F(n-1))
10+ const fib = ( N ) => {
11+ if ( N === 0 ) return [ 0 , 1 ]
12+ const [ a , b ] = fib ( Math . trunc ( N / 2 ) )
13+ const c = a * ( b * 2 - a )
14+ const d = a * a + b * b
15+ return N % 2 ? [ d , c + d ] : [ c , d ]
16+ }
17+
18+ const fastFibonacci = ( N ) => {
19+ if ( ! Number . isInteger ( N ) ) {
20+ throw new TypeError ( 'Input should be integer' )
21+ }
22+ return fib ( N ) [ 0 ]
23+ }
24+
25+ export { fastFibonacci }
Original file line number Diff line number Diff line change 1+ import { fastFibonacci } from '../FastFibonacciNumber'
2+
3+ describe ( 'Testing FibonacciNumber' , ( ) => {
4+ const errorCases = [ '0' , '12' , true ]
5+
6+ test . each ( errorCases ) ( 'throws an error if %p is invalid' , ( input ) => {
7+ expect ( ( ) => {
8+ fastFibonacci ( input )
9+ } ) . toThrow ( )
10+ } )
11+
12+ const testCases = [
13+ [ 0 , 0 ] ,
14+ [ 1 , 1 ] ,
15+ [ 10 , 55 ] ,
16+ [ 25 , 75025 ] ,
17+ [ 40 , 102334155 ]
18+ ]
19+
20+ test . each ( testCases ) ( 'if input is %i it returns %i' , ( input , expected ) => {
21+ expect ( fastFibonacci ( input ) ) . toBe ( expected )
22+ } )
23+ } )
You can’t perform that action at this time.
0 commit comments