问题
I have tried binary recursion to find the nth Fibonacci number (or the whole Fibonacci series by using a for
loop in main()
) but according to Data Structures and Algorithms in Java (6th Edition) by Michael T. Goodrich; it is a terribly inefficient method as it requires an exponential number of calls to the method. An efficient recursion technique is linear recursion given as follows;
/**Returns array containing the pair of Fibonacci numbers, F(n) and F(n-1)*/
public static long[] fibonacciGood(int n) {
if(n<=1) {
long[] answer = {n,0};
return answer;
}else {
long[] temp = fibonacciGood(n-1); //returns {F(n-1), F(n-2)
long[] answer = {temp[0]+temp[1], temp[0]}; //we want {F(n), F(n-1)}
return answer;
}
}
Whenever I run the code it returns a reference as [J@15db9742
which is not the desired answer. What should I write in main()
so that i can have the desired answer?
回答1:
Try the one below. You can refer the api here.
public static void main(String[] args) {
System.out.println(Arrays.toString(fibonacciGood(4)));
}
回答2:
You are trying to print out an array to the console, this is causing the memory address of the array to be output. You may want to iterate through the array returned, printing every element to get the desired output.
回答3:
Here you are printing the array object, so you are getting these results. Internally it calls toString method of the object, which return getClass().getName() + "@" + Integer.toHexString(hashCode());
. So you are getting value as [J@15db9742.
You can use convert is directly as below (Working in Java version 5 and above)
System.out.println(Arrays.toString(fibonacciGood(4)));
You can print it by converting it to list as below (in Java 8 or above) (Not Preferable to use streams here, but just for knowledge):
System.out.println(Arrays.stream(fibonacciGood(4)).boxed().collect(Collectors.toList()));
来源:https://stackoverflow.com/questions/58345788/computing-the-nth-fibonacci-number-using-linear-recursion