Fibonacci數列的一種經典遞迴實現

2021-08-29 10:34:09 字數 2608 閱讀 7323

剛才.net課程期末考試,正好最後一題考的是遞迴實現fibonacci數列.順便就把**打出來發在這裡.

(雖然沒什麼技術含量 :wink: )

主要特性就是使用buffer將先前已經計算過的fibonacci數列的值儲存下來,減少遞迴時的重複計算開銷.c#沒直接的lazy evaluation,這種採取buffer的策略應該是不錯的選擇吧.

另外,實現了ienumerable和ienumerable介面,方便遍歷fibonacci物件當前已經快取了的值.

由於該數列採用[color=blue]int[/color]表示,在下標超過46(包括)時就會溢位,所以在檢查下標後會拋異常,使用時需要注意.

[code]using system;

using system.collections.generic;

namespace testfibonacci

// demostrate the implementation of indexer

for ( int i = 10; i < 46; i++ ) }}

///

/// a class that calculates the fibonacci sequence

/// and buffers previously calculated values.

/// the fibonacci sequence described here starts

/// from index 0 with a value of 1.

/// because the return value is represented in an int,

/// this class does not support indexes larger than 46.

///

public class fibonacci : ienumerator

///

/// create an fibonacci instance with specified buffer length.

///

///

public fibonacci( int initlength )

#endregion

#region fibonacci member methods

///

/// initialize the buffer of fibonacci sequence.

///

/// length of buffer.

/// cannot exceed 46 or an overflowexception will be thrown

public void initializebuffer( int length ) will cause int to overflow",

( length - 1 ).tostring( ) ) );

calculate( length - 1 );

}///

/// recursively calculate the fibonacci sequence.

///

///

///

private int calculate( int index )

return this.buffer[ index ];

}public ienumeratorgetenumerator( )

#endregion

#region fibonacci member properties

///

/// read-only property for retrieving the

/// fibonacci sequence at specified index.

///

///

///

public int this[ int index ]

}#endregion

#region fibonacci member fields

///

/// buffers previously calculated values.

///

private listbuffer;

#endregion

#region ienumeratormembers

///

/// current enumerator cursor position.

///

private int position = -1;

public int current catch ( indexoutofrangeexception ) }}

#endregion

#region idisposable members

public void dispose( )

#endregion

#region ienumerator members

object system.collections.ienumerator.current

}public bool movenext( )

public void reset( )

#endregion}}

[/code]

Fibonacci數列的生成(4種方式)

1.定義 斐波那契數列 fibonacci sequence 又稱 分割數列 因數學家列昂納多 斐波那契 leonardoda fibonacci 以兔子繁殖為例子而引入,故又稱為 兔子數列 指的是這樣乙個數列 0 1 1 2 3 5 8 13 21 34 在數學上,斐波納契數列以如下被以遞迴的方法...

Fibonacci數列的兩種實現方式

斐波那契數列的形式為 1,1,2,3,5,8,13,21.從第三項開始,後面的每一項都是前面兩項的和。實現的方式有一下 兩種 一 遞迴方式實現 def fib n if n 1 print 數值錯誤!return 1 if n 1 or n 2 return 1 return fib n 1 fib...

一種快速求fibonacci第n個數的演算法

利用動態規則的思路,摒棄傳統的遞迴做法,可以得到一種快速的求fibonacci第n個數的演算法 求第n 從1開始 位fibonacci數 fibonacci數列前兩位為0,1.後面每一位數字等於前兩位數字之和 def fibonacci n if n 2 return n 1f 0 g 1 whil...