Computing the nth Fibonacci number using linear recursion [duplicate]

吃可爱长大的小学妹 提交于 2019-12-10 11:43:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!