- 方法一,递归的代码简单,但是效率很低,很讨厌在计算机里面用递归。
- 方法二,等于一种查表的方式,推荐。
- 方法三,要记得通项公式,相比于第二点,更快,但是数比较大的时候,方次运算容易溢出,需要设计独特的方法表示大数。
以下图片,中间的Label是用时。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 动态规划
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
long N = long.Parse(textBox1.Text);
textBox2.Text = fibonacci1(N).ToString();
sw.Stop();
label1.Text = sw.Elapsed.ToString();
}
private long fibonacci1(long N)
{
long Result = 0;
if (N == 0 || N == 1)
{
Result = 1;
}
else
{
Result = fibonacci1(N - 1) + fibonacci1(N-2);
}
return Result;
}
private void button2_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
long N = long.Parse(textBox1.Text);
textBox3.Text = fibonacci12(N).ToString();
sw.Stop();
label2.Text = sw.Elapsed.ToString();
}
private long fibonacci12(long N)
{
long Result = 0;
long[] fibonaccil = new long[200];
fibonaccil[0] = 1;
fibonaccil[1] = 1;
for (int i = 2; i <= N; i++)
{
fibonaccil[i] = fibonaccil[i - 2] + fibonaccil[i - 1];
}
Result = fibonaccil[N];
return Result;
}
private void button3_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
long N = long.Parse(textBox1.Text);
textBox4.Text = fibonacci13(N).ToString();
sw.Stop();
label3.Text = sw.Elapsed.ToString();
}
private long fibonacci13(long N)
{
long Result = 0;
N = N + 1;
Result=long.Parse((1/Math.Sqrt(5)*(Math.Pow((1+Math.Sqrt(5))/2,N)- Math.Pow((1 - Math.Sqrt(5)) / 2, N))).ToString());
return Result;
}
}
}