JAVA-fill in the TODO import java.util.Arrays; import stdlib.*; /** * -- The imp
ID: 3810907 • Letter: J
Question
JAVA-fill in the TODO
import java.util.Arrays;
import stdlib.*;
/**
* -- 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 long fibonacci (int n) {
return 0; // TODO
}
/**
* A test program, using private helper functions. See below.
* To make typing tests a little easier, I've written a function to convert strings to arrays. See below.
* You can modify this -- it is not graded.
*/
public static void main (String[] args) {
testSum ("11 21 81 -41 51 61");
testSum ("11 21 81 -41 51");
testSum ("11 21 81 -41");
testSum ("11 21 81");
testSum ("11 21");
testSum ("11");
testSum ("");
testReverse ("11 21 81 -41 51 61");
testReverse ("11 21 81 -41 51");
testReverse ("11 21 81 -41");
testReverse ("11 21 81");
testReverse ("11 21");
testReverse ("11");
testReverse ("");
testFibonacci (0, 0);
testFibonacci (1, 1);
testFibonacci (1, 2);
testFibonacci (2, 3);
testFibonacci (21, 8);
testFibonacci (75025, 25);
testFibonacci (233, 13);
testFibonacci (3416454622906707L, 76);
testFibonacci (-813251414217914645L, 376);
StdOut.println ("Finished tests");
draw (.5, .5, .25);
runTerribleLoop ();
}
Explanation / Answer
HI, Please find most efficient implementation of fibonacci function.
Please add this method in your program and test it.
public static long fibonacci (int n){
long a = 0, b = 1, c;
// base case
if (n == 0)
return a;
if(n == 1)
return b;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.