在C#中,可以利用斐波那契數列的數學性質來解決一些問題
using System;
class Program
{
static void Main()
{
int n = 10; // 生成前10個斐波那契數
for (int i = 0; i < n; i++)
{
Console.WriteLine(Fibonacci(i));
}
}
static int Fibonacci(int n)
{
if (n <= 1)
return n;
else
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
using System;
class Program
{
static void Main()
{
int n = 10; // 計算第10項
Console.WriteLine(Fibonacci(n));
}
static int Fibonacci(int n)
{
int[] memo = new int[n + 1];
memo[0] = 0;
memo[1] = 1;
for (int i = 2; i <= n; i++)
{
memo[i] = memo[i - 1] + memo[i - 2];
}
return memo[n];
}
}
using System;
class Program
{
static void Main()
{
int n = 10; // 計算第10項
Console.WriteLine(Fibonacci(n));
}
static long Fibonacci(int n)
{
if (n <= 1)
return n;
long[,] matrix = { { 1, 1 }, { 1, 0 } };
matrix = MatrixPower(matrix, n - 1);
return matrix[0, 0];
}
static long[,] MatrixPower(long[,] matrix, int n)
{
long[,] result = { { 1, 0 }, { 0, 1 } };
while (n > 0)
{
if ((n & 1) == 1)
result = MatrixMultiply(result, matrix);
matrix = MatrixMultiply(matrix, matrix);
n >>= 1;
}
return result;
}
static long[,] MatrixMultiply(long[,] a, long[,] b)
{
int rows = a.GetLength(0);
int cols = b.GetLength(1);
int inner = a.GetLength(1);
long[,] result = new long[rows, cols];
for (int i = 0; i< rows; i++)
{
for (int j = 0; j< cols; j++)
{
for (int k = 0; k< inner; k++)
{
result[i, j] += a[i, k] * b[k, j];
}
}
}
return result;
}
}
這些示例展示了如何在C#中利用斐波那契數列的數學性質來解決問題。你可以根據需要修改和擴展這些代碼。