利用递推求斐波那契数列

来源:互联网 发布:mac修改hosts文件翻墙 编辑:程序博客网 时间:2024/03/29 15:24

斐波那契数列

     1>1>2>3>5>8>13>21>34>55     1   2  3  4   5   6   7    8     9    10     f(1) = 1;     f(2) =1;     f(3) = f(1) + f(2) = 2     f(4) = f(2) + f(3) = 3     f(5) = f(3) + f(4) = 5     f(6) = f(4) + f(5) = 8     f(7) = f(5) + f(6) = 13     f(8) = f(6) + f(7) = 21     f(9) = f(7) + f(8) = 34     f(10) = f(8) + f(9) = 55

代码如下

class Test {    public static void main(String[] args) {            System.out.println(f(10));        }    public static int f(int num) {        if(num == 1 || num == 2) {            return 1;        }         //这里在方法内调用了自己的方法f()        return f(num - 1) + f(num - 2);    }}