首页 > 编程语言 > 详细

用Java实现菲波那切数列

时间:2019-08-07 19:32:27      阅读:155      评论:0      收藏:0      [点我收藏+]

一,递归方法

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实现菲波那切数列

原文:https://www.cnblogs.com/noperx/p/11317130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!