码迷,mamicode.com
首页 > 其他好文 > 详细

递归求斐波那契数列

时间:2015-03-20 18:00:15      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.Write("输入想求的斐波那契数列项数:");
            int n = Convert.ToInt32(Console.ReadLine());
            //递归实现
            Console.WriteLine("斐波那契数列数列算出的第{0}项为:{1}", n, NotNum(n));
            Console.ReadKey();
        }
        /// <summary>
        /// 非递归算法
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
       static int NotNum(int n)
        {
            int[] temp = { 1, 1 };


            if (n == 1 || n == 2)
            {
                return 1;
            }
            else
            {
                for (int i = 2; i < n; i++)
                {
                    int tp = temp[0] + temp[1];
                    temp[1] = temp[0];
                    temp[0] = tp;
                }
                return temp[0];
            }
        }


        /// <summary>
        /// 输入想求的斐波那契数列项数,这是一种递归的算法
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int Number(int n)
        {
            if (n <= 2)
            {
                return 1;
            }
            return Number(n - 1) + Number(n - 2);
        }

    }
}


 

递归求斐波那契数列

标签:

原文地址:http://www.cnblogs.com/workcn/p/4353781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!