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);

            }
        }
    }

  • 相关阅读:
    python加载csv数据
    Android项目依赖库管理方式简介
    Android PhotoView基本功能实现
    Android ListView的header footer设置visibility gone不起作用
    [干货][EMIT]千行代码实现代理式AOP+属性的自动装配
    Emit实现DataRow转化成强类型的T
    有关docker新版的icc、iptables的一个巨坑
    Mac神器Iterm2的Shell Integration的用法和注意事项
    生成ssl证书文件
    python3 module中__init__.py的需要注意的地方
  • 原文地址:https://www.cnblogs.com/kexb/p/5087150.html
Copyright © 2011-2022 走看看