zoukankan      html  css  js  c++  java
  • 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);

            }
        }
    }

  • 相关阅读:
    不务正业系列-浅谈《过气堡垒》,一个RTS玩家的视角
    [LeetCode] 54. Spiral Matrix
    [LeetCode] 40. Combination Sum II
    138. Copy List with Random Pointer
    310. Minimum Height Trees
    4. Median of Two Sorted Arrays
    153. Find Minimum in Rotated Sorted Array
    33. Search in Rotated Sorted Array
    35. Search Insert Position
    278. First Bad Version
  • 原文地址:https://www.cnblogs.com/kexb/p/5087150.html
Copyright © 2011-2022 走看看