斐波那契数列

斐波那契数列:1、1、2、3、5、8、13、21、34、55……

F(n) = F(n-1) + F(n-2)
F(1) = 1
F(2) = 1

实现

1.普通

class Fibonacci {
    public static void main(String[] args) {
        f1(10);
    }
    private static void f1(int n) {
        int n1 = 1;
        int n2 = 1;
        System.out.println(n1);
        System.out.println(n2);
        int n3 = 0;
        for (int i = 3; i <= n; i++) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.println(n3);
        }
    }
}
  1. 数组
private static void f2(int n) {
        int [] array = new int[n];
        array[0] = 1;
        array[1] = 1;
        System.out.println(array[0]);
        System.out.println(array[1]);
        for (int i = 2; i < n; i++) {
            array[i] = array[i-1] + array[i-2];
            System.out.println(array[i]);
        }
    } 
  1. 递归(在外面循环)
public class Fibonacci {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(f3(i));
        }
    }

    static long f3(int n) {
        if (n <= 2) {
            return 1;
        } else {
            return aFunc(n - 1) + aFunc(n - 2);
        }
    }

}

你可能感兴趣的:(斐波那契数列)