fibnacci数列的两种实现(递归实现和循环实现)

//一切尽在规律中,认真观察,你会明白更多...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {

            int i = 0;
            SimulationFib();

            Console.ReadKey();
        }
        public static void SimulationFib()
        {

            int n = 31;
            Console.WriteLine("Fib数列的递归实现........");
            #region Fib数列的递归实现
            for (int i = 1; i <= 32; i++)
            {
                Console.WriteLine(string.Format("Fib序列的第{0}项的值为:{1}", i, Fib(i)));

            }
            #endregion
            Console.WriteLine("------------------------------");

            Console.WriteLine("Fib数列的常规实现.............");

            for (int i=1; i<=32; i++)
            {
                Console.WriteLine(string.Format("Fib序列的第{0}项的值为:{1}", i, fib(i)));
            }
        }
        /// <summary>
        /// fib数列的循环实现
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int fib(int n)
        {
            if (n == 1 || n == 2)
            {
                return 1;
            }
            // 1 1 2 3
            int a = 1;
            int b = 1;
            int t = 0;
            for(int i=1;i<=n-2;i++)
            {

                t = a;
                a = b;
                b = t + a;
               
               
            }

            return b;
        }
        /// <summary>
        /// fib序列的递归实现
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int Fib(int n)
        {
            if (n == 1 || n == 2)
            {
                return 1;

            }

            return Fib(n - 1) + Fib(n - 2);

        }
    }
}

原文地址:https://www.cnblogs.com/kexb/p/5087150.html