From 908c4ed26ea00142da5e1a2f2a2f8e58c721d0da Mon Sep 17 00:00:00 2001 From: Luis Leiva <103515231+Luislev@users.noreply.github.com> Date: Sun, 5 Nov 2023 23:12:41 -0500 Subject: [PATCH 1/2] Update fibonacci-solution.js --- 10_fibonacci/solution/fibonacci-solution.js | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/10_fibonacci/solution/fibonacci-solution.js b/10_fibonacci/solution/fibonacci-solution.js index acdd1e0..5e3ff40 100644 --- a/10_fibonacci/solution/fibonacci-solution.js +++ b/10_fibonacci/solution/fibonacci-solution.js @@ -1,17 +1,12 @@ const fibonacci = function(count) { if (count < 0) return "OOPS"; if (count === 0) return 0; - - let firstPrev = 1; - let secondPrev = 0; + const fib = [0, 1]; for (let i = 2; i <= count; i++) { - let current = firstPrev + secondPrev; - secondPrev = firstPrev; - firstPrev = current; + fib[i] = fib[i - 1] + fib[i - 2]; } - - return firstPrev; + return fib[count]; }; module.exports = fibonacci; From 123e00d9331a80312bd459cbadd663f684a28963 Mon Sep 17 00:00:00 2001 From: Luis Leiva <103515231+Luislev@users.noreply.github.com> Date: Tue, 7 Nov 2023 21:27:27 -0500 Subject: [PATCH 2/2] Add alternative solution in fibonacci-solution.js --- 10_fibonacci/solution/fibonacci-solution.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/10_fibonacci/solution/fibonacci-solution.js b/10_fibonacci/solution/fibonacci-solution.js index 5e3ff40..644edbb 100644 --- a/10_fibonacci/solution/fibonacci-solution.js +++ b/10_fibonacci/solution/fibonacci-solution.js @@ -1,12 +1,25 @@ const fibonacci = function(count) { if (count < 0) return "OOPS"; if (count === 0) return 0; - - const fib = [0, 1]; + + let firstPrev = 1; + let secondPrev = 0; + for (let i = 2; i <= count; i++) { - fib[i] = fib[i - 1] + fib[i - 2]; + let current = firstPrev + secondPrev; + secondPrev = firstPrev; + firstPrev = current; } - return fib[count]; + + return firstPrev; + }; +// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1. +// const fib = [0, 1]; +// for (let i = 2; i <= count; i++) { +// fib[i] = fib[i - 1] + fib[i - 2]; +// } +// return fib[count]; + module.exports = fibonacci;