斐波那契数列(递归和非递归)

递归写法:

public class Homework3 {
    public int Fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
}

非递归写法:

public class Homework3 {
    public int Fibonacci(int n) {

        if (n == 0){
            return 0;
        }
        if (n==1 || n == 2){
            return 1;
        }
        int first = 1;
        int second = 1;
        int result = 0;
        for (int i = 3;i<=n;i++){
            result = first + second;
            first = second;
            second = result;
        }
        return result;
    }
}
posted @ 2020-07-07 21:36  硬盘红了  阅读(179)  评论(0编辑  收藏  举报