C#用遞歸算法實現(xiàn):一列數(shù)的規(guī)則如下: 1、1、2、3、5、8、13、21、34,求第30位數(shù)是多少
更新時間:2016年06月16日 09:29:44 作者:Robin
本文主要介紹三種方法,解決面試中常見的問題,求第30位數(shù)是多少的問題,希望能給大家一個參考。
方法一:遞歸算法
/// <summary> /// 一列數(shù)的規(guī)則如下: 1、1、2、3、5、8、13、21、34求第30位數(shù)是多少, 用遞歸算法實現(xiàn)。(C#語言) /// </summary> /// <param name="pos"></param> /// <returns></returns> public int GetNumberAtPos(int pos) { if(pos==0||pos==1) { return 1; } int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2); return res; }
方法二:不用遞歸
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Test { public class Class1 { private ArrayList list = new ArrayList(); public Class1() { } public Class1(int num) : base() { int i; for (i = 1; i <= num; i++) { list.Add(Calculation(i)); } } private int Calculation(int num) { if (num == 1 || num == 2) return 1; else return Convert.ToInt32(list[num - 2]) + Convert.ToInt32(list[num - 3]); } public int Calculation() { return Convert.ToInt32(list[list.Count - 1]); } } public class test { public static void Main() { int j; int num; for (j = 1; j < 100; j++) { Console.WriteLine("你要計算第多少位:"); string readstr; readstr = Console.ReadLine(); if (!string.IsNullOrEmpty(readstr)) { if (int.TryParse(readstr, out num)) { if (num < 1) continue; else { Class1 c1 = new Class1(num); Console.WriteLine(c1.Calculation()); } } else { continue; } } else { break; } } } } }
方法三:用循環(huán)實現(xiàn)
public long getNumber(int pos) { long one = 1; long two = 1; if (pos == 0 || pos == 1) { return 1; } int i = 3; long sum = 1; while (i <= pos) { sum = one + two; one = two; two = sum; i++; } return sum; }
以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在C#中List集合使用First()方法獲取第一個元素的操作
這篇文章主要介紹了在C#中List集合使用First()方法獲取第一個元素的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12WPF實現(xiàn)雷達圖(仿英雄聯(lián)盟)的示例代碼
這篇文章主要介紹了如何利用WPF實現(xiàn)雷達圖(仿英雄聯(lián)盟)的繪制,文中的示例代碼講解詳細,對我們學習或工作有一定幫助,需要的可以參考一下2022-07-07C#中GridView動態(tài)添加列的實現(xiàn)方法
這篇文章主要介紹了C#中GridView動態(tài)添加列的實現(xiàn)方法,涉及C#中GridView的相關使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07C#實現(xiàn)圖片上傳(PC端和APP)保存及 跨域上傳說明
這篇文章主要介紹了C#實現(xiàn)圖片上傳(PC端和APP)保存及 跨域上傳說明的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12