在C#中,可以使用不同的方法来测试斐波那契数列
public static int FibonacciRecursive(int n)
{
if (n <= 1)
return n;
else
return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
}
public static int FibonacciIterative(int n)
{
if (n <= 1)
return n;
int a = 0;
int b = 1;
int result = 0;
for (int i = 2; i <= n; i++)
{
result = a + b;
a = b;
b = result;
}
return result;
}
public static int FibonacciDynamic(int n)
{
if (n <= 1)
return n;
int[] fibArray = new int[n + 1];
fibArray[0] = 0;
fibArray[1] = 1;
for (int i = 2; i <= n; i++)
{
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
}
return fibArray[n];
}
public static int FibonacciMatrix(int n)
{
if (n <= 1)
return n;
int[,] matrix = { { 1, 1 }, { 1, 0 } };
MatrixPower(matrix, n - 1);
return matrix[0, 0];
}
private static void MatrixPower(int[,] matrix, int n)
{
if (n <= 1)
return;
MatrixPower(matrix, n / 2);
MultiplyMatrix(matrix, matrix);
if (n % 2 != 0)
{
int[,] tempMatrix = { { 1, 1 }, { 1, 0 } };
MultiplyMatrix(matrix, tempMatrix);
}
}
private static void MultiplyMatrix(int[,] matrixA, int[,] matrixB)
{
int x = matrixA[0, 0] * matrixB[0, 0] + matrixA[0, 1] * matrixB[1, 0];
int y = matrixA[0, 0] * matrixB[0, 1] + matrixA[0, 1] * matrixB[1, 1];
int z = matrixA[1, 0] * matrixB[0, 0] + matrixA[1, 1] * matrixB[1, 0];
int w = matrixA[1, 0] * matrixB[0, 1] + matrixA[1, 1] * matrixB[1, 1];
matrixA[0, 0] = x;
matrixA[0, 1] = y;
matrixA[1, 0] = z;
matrixA[1, 1] = w;
}
这些方法都可以用于测试斐波那契数列。你可以根据需要选择合适的方法。