数据结构-Java01.两种斐波那契数列算法实现

public class Test {

    /**斐波那契数列1*/
    public  static  int fib1(int n) {
        if(n <=1) return n;
        else
            return fib1(n-1) + fib1(n-2);
    }

    /**斐波那契数列2*/
    public static int fib2(int n) {
        if(n <= 1) return n;
        int first = 0;
        int second = 1;
        for (int i = 0; i < n - 1; i++) {
            int sum = first + second;
            first =second;
            second = sum;
        }
        return second;
    }

    /**两个数相加之和1*/
    public static int sum1(int n) {
        int result = 0;
        for (int i = 1; i <= n; i++) {
            result +=i;
        }
        return result;
    }

    /**两个数相加之和2*/
    public static int sum2(int n) {
        return n*(n+1)/2;
    }

    public static void main(String[] args) {
        int n = 20;
        System.out.println(fib1(n));
        System.out.println(fib2(n));

        System.out.println(sum1(n));
        System.out.println(sum2(n));
    }

}

你可能感兴趣的:(数据结构-Java01.两种斐波那契数列算法实现)