Skip to content
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
33 changes: 16 additions & 17 deletions fixme.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
public class FibonacciChallenge {
public class fixme {

public static void main(String[] args) {
// Fix me: Should we allow negative numbers as input?
System.out.println("Fibonacci(5) = " + fibonacci(5));
System.out.println("Fibonacci(10) = " + fibonacci(10));

// Fix me: What happens with this test case?
System.out.println("First 8 Fibonacci numbers:");
printFibonacciSequence(8);

Expand All @@ -14,34 +12,35 @@ public static void main(String[] args) {
}

public static int fibonacci(int n) {
// Fix me: Remember, Fibonacci sequence starts with 0, 1, ...
if (n < 0) {
throw new IllegalArgumentException("Input must be a non-negative integer.");
}
if (n == 0) return 0;
if (n == 1) return 1;

return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void printFibonacciSequence(int n) {
// Fix me: Off-by-one error?
for (int i = 1; i <= n; i++) {
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
System.out.println();
}

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) {
return a;
if (n < 0) {
throw new IllegalArgumentException("Input must be a non-negative integer.");
}
if (n == 0) return 0;
if (n == 1) return 1;

for (int i = 2; i < n; i++) {
int temp = a;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int temp = a + b;
a = b;
b = temp + a;
b = temp;
}

return b;
}
}
}