递归求斐波那契数列
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); } } }
本文作者:anekos
本文链接:https://www.cnblogs.com/workcn/p/4353781.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步