首页主机资讯C#中斐波那契数列的测试方法有哪些

C#中斐波那契数列的测试方法有哪些

时间2024-09-10 16:20:03发布访客分类主机资讯浏览1159
导读:在C#中,可以使用不同的方法来测试斐波那契数列 递归方法: public static int FibonacciRecursive(int n { if (n <= 1 return n; e...

在C#中,可以使用不同的方法来测试斐波那契数列

  1. 递归方法:
public static int FibonacciRecursive(int n)
{
    
    if (n <
    = 1)
        return n;
    
    else
        return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);

}

  1. 迭代方法:
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;

}

  1. 使用动态规划(自底向上):
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];

}

  1. 使用矩阵乘法:
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;

}
    

这些方法都可以用于测试斐波那契数列。你可以根据需要选择合适的方法。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: C#中斐波那契数列的测试方法有哪些
本文地址: https://pptw.com/jishu/698322.html
Linux中GRUB的启动菜单如何自定义 Linux中GRUB的启动项如何管理

游客 回复需填写必要信息