Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA PROBLEM 5: The implementation of terribleFibonacci is TERRIBLE! Write a * m

ID: 3906404 • Letter: J

Question

JAVA

PROBLEM 5: The implementation of terribleFibonacci is TERRIBLE! Write a

               * more efficient version of fibonacci. Do not change runFibonacciLoop or

               * runFibonacciSomeValues.

               *

               * To make fibonacci run faster, you want it so that each call to

               * fibonacci(n) computes the fibonacci numbers between 0 and n once, not

               * over and over again.

               *

               * Comment: You will want to use a local variable of type "long" rather than

               * type "int", for the reasons discussed above.

               *

               * Comment: At some point, your fibonacci numbers might become negative.

               * This is normal and expected.

               * http://en.wikipedia.org/wiki/Integer_overflow We discuss this at length

               * in our systems classes.

               *

               * You may not use any "fields" to solve this problem (a field is a variable

               * that is declared "outside" of the function declaration --- either before

               * or after).

               */

               public static void runFibonacciLoop () {

                              for (int N = 0; N < 100; N++)

                                             StdOut.format ("fibonacci(%2d)=%d ", N, fibonacci (N));

               }

               public static void runFibonacciSomeValues () {

                              StdOut.format ("fibonacci(%2d)=%d ", 13, fibonacci (13));

                              StdOut.format ("fibonacci(%2d)=%d ", 7, fibonacci (7));

                              StdOut.format ("fibonacci(%2d)=%d ", 21, fibonacci (21));

               }

               public static long fibonacci (int n) {

                              return 0; // TODO

               }

Explanation / Answer

public static long fibonacci (int n) { int n1 = 0, n2 = 1, temp; if(n == 1) { return n1; } else if(n == 2) { return n2; } else { for(int i = 3; i