斐波那契数列 递归/非递归

        static int Fn(int n)
        {
            if (n <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (n == 1 || n == 2)
            {
                return 1;
            }
            return checked(Fn(n - 1) + Fn(n - 2)); // when n>46 memory will overflow
        }



    static long Fib3(long num)
    {
        if (num < 0)
        {
            throw new ArgumentOutOfRangeException("num", "num必须大于等于0");
        }
        if (num == 1 || num == 2)
        {
            return 1;
        }

        long first = 0;
        long second = 1;
        long third = 0;

        for (int i = 2; i <= num; i++)
        {
            third = first + second;
            first = second;
            second = third;
        }

        return third;
    }

你可能感兴趣的:(算法,数据结构)