查找斐波纳契数列中第 N 个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Primary_wind/article/details/80403428

题目

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

前2个数是 0 和 1 。
第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …

解法

public class Fibonacci {

    public static void main(String[] args) {
        fibonacci(5);
    }

    public static int fibonacci(int n) {
        if (n == 1) {
            return 0;
        }
        if (n == 2) {
            return 1;
        }
        int one = 0;
        int two = 1;
        int sum = 0;
        for (int i = 1; i < n - 1; i++) {
            sum = one + two;
            one = two;
            two = sum;
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/Primary_wind/article/details/80403428
今日推荐