File tree Expand file tree Collapse file tree 3 files changed +10
-5
lines changed
src/algorithms/math/fibonacci Expand file tree Collapse file tree 3 files changed +10
-5
lines changed Original file line number Diff line number Diff line change 33 * Time complexity: O(n)
44 * Space complexity: O(n)
55 * @param {number } length Length of the Fibonacci sequence.
6- * @returns {number [] } Fibonacci sequence of the specified length.
6+ * @returns {bigint [] } Fibonacci sequence of the specified length.
77 */
88const fibonacciSequence = ( length ) => {
99 if ( length === 0 ) return [ ]
@@ -12,7 +12,9 @@ const fibonacciSequence = (length) => {
1212 const sequence = [ 0n , 1n ]
1313
1414 for ( let index = 2 ; index < length ; index ++ ) {
15- sequence . push ( sequence . at ( - 1 ) + sequence . at ( - 2 ) )
15+ const idxMinOne = sequence . at ( - 1 ) ?? 0n
16+ const idxMinTwo = sequence . at ( - 2 ) ?? 0n
17+ sequence . push ( idxMinOne + idxMinTwo )
1618 }
1719
1820 return sequence
Original file line number Diff line number Diff line change 33 * Time complexity: O(n)
44 * Space complexity: O(n)
55 * @param {number } length Length of the Fibonacci sequence.
6- * @returns {number [] } Fibonacci sequence of the specified length.
6+ * @returns {bigint [] } Fibonacci sequence of the specified length.
77 */
88const fibonacciSequence = ( length ) => {
99 const fibos = [ 0n , 1n ]
1010 if ( length < 2 ) return fibos . slice ( 0 , length )
1111
1212 return [ ...Array ( length - 2 ) . keys ( ) ] . reduce ( fibos => {
13- fibos . push ( fibos . at ( - 1 ) + fibos . at ( - 2 ) )
13+ const idxMinOne = fibos . at ( - 1 ) ?? 0n
14+ const idxMinTwo = fibos . at ( - 2 ) ?? 0n
15+ fibos . push ( idxMinOne + idxMinTwo )
1416 return fibos
1517 } , fibos )
1618}
Original file line number Diff line number Diff line change 33 * Time complexity: O(n)
44 * Space complexity: O(n)
55 * @param {number } length Length of the Fibonacci sequence.
6- * @returns {number [] } Fibonacci sequence of the specified length.
6+ * @returns {bigint [] } Fibonacci sequence of the specified length.
77 */
88const fibonacciSequence = ( length ) => {
99 if ( length === 0 ) return [ ]
1010 if ( length === 1 ) return [ 0n ]
1111
1212 const sequence = [ 0n , 1n ]
1313
14+ /** @param {number } n */
1415 const fibo = ( n ) => {
1516 if ( typeof sequence [ n ] !== 'undefined' ) return sequence [ n ]
1617 sequence [ n ] = fibo ( n - 1 ) + fibo ( n - 2 )
You can’t perform that action at this time.
0 commit comments