File tree 3 files changed +10
-5
lines changed
src/algorithms/math/fibonacci
3 files changed +10
-5
lines changed Original file line number Diff line number Diff line change 3
3
* Time complexity: O(n)
4
4
* Space complexity: O(n)
5
5
* @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.
7
7
*/
8
8
const fibonacciSequence = ( length ) => {
9
9
if ( length === 0 ) return [ ]
@@ -12,7 +12,9 @@ const fibonacciSequence = (length) => {
12
12
const sequence = [ 0n , 1n ]
13
13
14
14
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 )
16
18
}
17
19
18
20
return sequence
Original file line number Diff line number Diff line change 3
3
* Time complexity: O(n)
4
4
* Space complexity: O(n)
5
5
* @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.
7
7
*/
8
8
const fibonacciSequence = ( length ) => {
9
9
const fibos = [ 0n , 1n ]
10
10
if ( length < 2 ) return fibos . slice ( 0 , length )
11
11
12
12
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 )
14
16
return fibos
15
17
} , fibos )
16
18
}
Original file line number Diff line number Diff line change 3
3
* Time complexity: O(n)
4
4
* Space complexity: O(n)
5
5
* @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.
7
7
*/
8
8
const fibonacciSequence = ( length ) => {
9
9
if ( length === 0 ) return [ ]
10
10
if ( length === 1 ) return [ 0n ]
11
11
12
12
const sequence = [ 0n , 1n ]
13
13
14
+ /** @param {number } n */
14
15
const fibo = ( n ) => {
15
16
if ( typeof sequence [ n ] !== 'undefined' ) return sequence [ n ]
16
17
sequence [ n ] = fibo ( n - 1 ) + fibo ( n - 2 )
You can’t perform that action at this time.
0 commit comments