在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#中利用斐波那契数列的数学性质来解决问题。你可以根据需要修改和扩展这些代码。