您的位置:首页 > 其它

斐波那契数列数列递归与非递归方式实现

2017-10-10 12:53 363 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace 递归实现斐波那契数列

{

    class Program

    {

        /*返回第n个斐波那契数列项的值*/

        static int Fibonacci(int n) {

            /*斐波那契数列的前两项都是1*/

            if ((1 == n) || (2 == n))

            {

                return 1;

            }

            else {

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

            }

        }

        static void Main(string[] args)

        {

            Console.Write("输入总项数:");

            int n = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Fibonacci:");

            for (int i = 1; i <= n; i++) {

                Console.Write("{0}\t",Fibonacci(i));

                /*输出五个换一行*/

                if (i % 5 == 0)

                    Console.WriteLine();

            }

            Console.ReadKey();

        }

    }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace 非递归实现斐波那契数列

{

    class Program

    {

        static void Main(string[] args)

        {

            //搞一个能存30个数的long类型数组

            long[] a = new long[30];

            a[0] = 1;

            a[1] = 1;

            for (int j = 2; j < 30; j++) {

                a[j] = a[j - 1] + a[j - 2];

            }

            int count = 0;

            foreach (int item in a) {

                Console.Write("{0}\t",item);

                count++;

                if (item % 5 == 0) {

                    Console.WriteLine();

                }

            }

            Console.ReadKey();

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: