Skip to content

Update fixme.java #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions fixme.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ public static void main(String[] args) {

public static int fibonacci(int n) {
// Fix me: Remember, Fibonacci sequence starts with 0, 1, ...

if (n < 0) { //base case added!!
throw new IllegalArgumentException("Input cannot be negative.");
} else if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

Expand All @@ -28,20 +34,22 @@ public static void printFibonacciSequence(int n) {
}

public static int efficientFibonacci(int n) {
// Fix me: How can you avoid recalculating the same Fibonacci numbers repeatedly?
int a = 0;
int b = 1;

if (n < 0) {
throw new IllegalArgumentException("Input cannot be negative.");
}
if (n == 0) {
return a;
return 0;
}

for (int i = 2; i < n; i++) {
int temp = a;
if (n == 1) {
return 1;
}

int a = 0, b = 1;
for (int i = 2; i <= n; i++) { // Loop should run till n
int temp = a + b;
a = b;
b = temp + a;
b = temp;
}

return b;
}
}