費式數列的特性式是後面的數字等於前面2個數字的加總
例如,0,1,1,2,3,5,8
一種是用遞迴方式如下
static void Main(string[] args)
{
int number = 6;
for (int i = 1; i <= number; i++)
{
Console.WriteLine(Fibonacc(i).ToString());
}
}
private static int Fibonacc(int n)
{
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
return Fibonacc(n - 1) + Fibonacc(n - 2);
}
另外一種是單純 for 迴圈的暴力解法
static void Main(string[] args)
{
int number = 6;
for (int i = 1; i <= number; i++)
{
Console.WriteLine(Fibonacc2(i).ToString());
}
}
/// <summary>
/// 費氏數列 0,1,1,2,3,5,8.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private static int Fibonacc2(int n)
{
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
int prev = 1;
int curr = 1;
for (int i = 3; i <= n; i++)
{
int sum = prev + curr;
prev = curr;
curr = sum;
}
return curr;
}
感謝分享,感覺蠻有趣的,順手用JS寫了一個版本~
function getFString(n, first = 0, second = 1){
let fArray = [first, second];
while(fArray.length < n){
let fArrayLen = fArray.length;
let curr = fArray[fArrayLen -1]
let pre = fArray[fArrayLen -2]
fArray.push(curr + pre)
}
console.log(fArray)
}
getFString(7) // [0, 1, 1, 2, 3, 5, 8]
感謝分享,感覺蠻有趣的,順手用JS寫了一個版本~
function getFString(n, first = 0, second = 1){
let fArray = [first, second];
while(fArray.length < n){
let fArrayLen = fArray.length;
let curr = fArray[fArrayLen -1]
let pre = fArray[fArrayLen -2]
fArray.push(curr + pre)
}
console.log(fArray)
}
getFString(7) // [0, 1, 1, 2, 3, 5, 8]