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

            }
        }
    }

  • 相关阅读:
    Oracle startup startup nomount startup mount 的区别
    Linux 查看磁盘是否为SSD
    Spark入门实战系列--4.Spark运行架构
    Hbase 的java 增删改查操作
    Hbase 的一些重要网站链接,有空没空的搂两眼
    一段生成大数据测试数据的java code 片段
    一段简单的java 代码,用于日期格式转化
    一个简单的jsp 页面
    Scala 版 word count
    db2expln 查看执行plan
  • 原文地址:https://www.cnblogs.com/kexb/p/5087150.html
Copyright © 2011-2022 走看看