编程语言
首页 > 编程语言> > 用Java实现菲波那切数列

用Java实现菲波那切数列

作者:互联网

一,递归方法

public class Febonacci {

    public static int fn(int n){
            if (n < 0 ){
                throw new IllegalArgumentException(n + "必须大于零");
            }
            if (n==0 || n==1){
                return 1;
            }
            return fn(n-1)+ fn(n-2);
    }

    public static List<Integer> foo(int n){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            list.add(fn(i));
        }
        return list;
    }

    public static void main(String[] args) {

        System.out.println(foo(6));
    }
}

 

二,循环迭代方法

public class Febonacci2 {

    public static int fn(int n){
            if (n < 0 ){
                throw new IllegalArgumentException(n + "必须大于零");
            }
            if (n==0 || n==1){
                return 1;
            }
            int i = 1;
            int j = 1;
            int sum = 0;

        for (int k = 2; k <= n; k++) {
            sum = i + j;
            i = j;
            j = sum;
        }
        return sum;
    }

    public static List<Integer> foo(int n){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            list.add(fn(i));
        }
        return list;
    }

    public static void main(String[] args) {

        System.out.println(foo(2));
    }
}

 

标签:Java,int,那切,return,static,菲波,new,public,fn
来源: https://www.cnblogs.com/noperx/p/11317130.html