斐波那契数列

/**
 * 斐波那契
 * @author 玖洲林
 * Create Time 2019-08-17 下午 07:03
 */
public class Fibonacci {
    public static void main(String[] args) {
        int num = getFibonacci(7);
        System.out.println(num);
    }
    // 1 1 2 3 5 8 13
    private static int getFibonacci(int index) {
        if(index < 0) {
            return -1;
        } else if (index == 0){
            return 0;
        } else if (index <= 2){
            return 1;
        } else {
            int c = 0,b = 1,a = 1;
            for (int i = 3; i <= index; i++) {
                c = a + b;
                a = b;
                b = c;
            }
            return c;
        }
    }
}

发表评论