File tree Expand file tree Collapse file tree 2 files changed +17
-1
lines changed Expand file tree Collapse file tree 2 files changed +17
-1
lines changed Original file line number Diff line number Diff line change @@ -56,3 +56,18 @@ export const nthFibonacciRecursively = (number: number): number => {
56
56
nthFibonacciRecursively ( number - 1 ) + nthFibonacciRecursively ( number - 2 )
57
57
) ;
58
58
} ;
59
+
60
+
61
+ /**
62
+ * @param number The index of the number in the Fibonacci sequence.
63
+ * @return The Fibonacci number on the nth index in the sequence.
64
+ * @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
65
+ * @see : https://math.hmc.edu/funfacts/fibonacci-number-formula/
66
+ * @author : dev-madhurendra<https://github.com/dev-madhurendra>
67
+ */
68
+
69
+ const sqrt5 = Math . sqrt ( 5 )
70
+ const phi = ( 1 + sqrt5 ) / 2
71
+ const psi = ( 1 - sqrt5 ) / 2
72
+
73
+ export const nthFibonacciUsingFormula = ( n : number ) => Math . round ( ( phi ** n - psi ** n ) / sqrt5 )
Original file line number Diff line number Diff line change 1
- import { nthFibonacci , nthFibonacciRecursively } from '../fibonacci' ;
1
+ import { nthFibonacciUsingFormula , nthFibonacci , nthFibonacciRecursively } from '../fibonacci' ;
2
2
3
3
const test = ( func : ( n : number ) => number ) =>
4
4
it . each ( [
@@ -11,3 +11,4 @@ const test = (func: (n: number) => number) =>
11
11
] ) ( 'fib(%i) = %i' , ( n , expected ) => expect ( func ( n ) ) . toBe ( expected ) ) ;
12
12
describe ( 'Fibonacci iterative' , ( ) => test ( nthFibonacci ) ) ;
13
13
describe ( 'Fibonacci recursive' , ( ) => test ( nthFibonacciRecursively ) ) ;
14
+ describe ( 'Fibonacci Using formula' , ( ) => test ( nthFibonacciUsingFormula ) ) ;
You can’t perform that action at this time.
0 commit comments