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

            }
        }
    }

  • 相关阅读:
    Android应用程序与SurfaceFlinger服务的关系概述和学习计划【转】
    Linux内核的LED设备驱动框架【转】
    电源管理-4种休眠方式状态
    linux 管道,输出重定向,后端执行
    find 和grep的区别
    linux启动脚本
    linux启动介绍
    sudo的使用
    ps aux|grep *** 解释
    php图片防盗链
  • 原文地址:https://www.cnblogs.com/kexb/p/5087150.html
Copyright © 2020-2023  润新知