C#中斐波那契数列的数学性质应用
导读:在C#中,可以利用斐波那契数列的数学性质来解决一些问题 生成斐波那契数列: using System; class Program { static void Main( { int n = 10;...
在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);
}
}
- 计算斐波那契数列的第n项(使用动态规划):
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];
}
}
- 计算斐波那契数列的第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#中利用斐波那契数列的数学性质来解决问题。你可以根据需要修改和扩展这些代码。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C#中斐波那契数列的数学性质应用
本文地址: https://pptw.com/jishu/698424.html