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 => {
5656 nthFibonacciRecursively ( number - 1 ) + nthFibonacciRecursively ( number - 2 )
5757 ) ;
5858} ;
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' ;
22
33const test = ( func : ( n : number ) => number ) =>
44 it . each ( [
@@ -11,3 +11,4 @@ const test = (func: (n: number) => number) =>
1111 ] ) ( 'fib(%i) = %i' , ( n , expected ) => expect ( func ( n ) ) . toBe ( expected ) ) ;
1212describe ( 'Fibonacci iterative' , ( ) => test ( nthFibonacci ) ) ;
1313describe ( 'Fibonacci recursive' , ( ) => test ( nthFibonacciRecursively ) ) ;
14+ describe ( 'Fibonacci Using formula' , ( ) => test ( nthFibonacciUsingFormula ) ) ;
You can’t perform that action at this time.
0 commit comments