Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c1508a8

Browse files
handling fibonacci for negative numbers and 0
1 parent ef16476 commit c1508a8

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

‎src/_Classics_/fibonacci/index.js‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
//The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
12
// the algorithm has time complexity of O(n^2), very bad!
23
function fibonacci(position) {
34
// if position is 1 or 2, the number in fibonacci sequence will be 1
4-
if (position <3) {
5-
return 1;
5+
if (position <=1) {
6+
return position;
67
}
8+
79
// else the element in fibonacci sequence will be the sum of
810
// element at position(p) (p -1) and (p - 2)
911
return fibonacci(position - 2) + fibonacci(position - 1);
@@ -24,8 +26,8 @@ function fibonacciMemoized(index, cache) {
2426
if (cache[index]) {
2527
return cache[index];
2628
} else {
27-
if (index <3) {
28-
return 1;
29+
if (index <=1) {
30+
return index;
2931
} else {
3032
cache[index] =
3133
fibonacciMemoized(index - 1, cache) +
@@ -41,7 +43,9 @@ function fibonacciMemoized(index, cache) {
4143

4244
function fibonacciTabular(n) {
4345
const table = [0, 1];
44-
46+
if (n <= 1) {
47+
return n;
48+
}
4549
for (let i = 2; i <= n; i += 1) {
4650
table[i] = table[i - 1] + table[i - 2];
4751
}
@@ -54,4 +58,4 @@ function fibonacciTabular(n) {
5458
// console.log(`Fib normal - ${fibonacci(number)}`);
5559
// console.log('--');
5660
// console.log(`Fib memo - ${fibonacciMemoized(number)}`);
57-
// console.log(`Fib table - ${fibonacciTabular(number)}`);
61+
// console.log(`Fib table - ${fibonacciTabular(number)}`);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /