斐波那契(Fibonacci)数列的计算效率

方法1:

直接递归,调用button1_Click函数,当N为41时耗时10644ms,递归调用次数count = 535828591(5亿),已经没有信心再增加N的值了。

效率低的原因是每次求N的结果时都会重新计算N-1和N-2的结果,导致大量的重复计算,由count的值可知。

 

方法2:

用一字典保存每次计算后的第N项的值,下次需要时直接取,不需重复计算。

当N=41时耗时1ms以下,递归次数81,即便N=150时耗时也在1ms以下。

 

结论:

在递归算法时,考虑暂存结果减少递归调用次数能极大提高运算效率。

 

以下是主要代码:

private Dictionary<long, long> dict = new Dictionary<long, long>();
        private long count;

        private long Fibonacci1(long N)
        {
            count++;
            if (N <= 1)
                return N;
            return Fibonacci1(N - 1) + Fibonacci1(N - 2);
        }

        private long Fibonacci2(long N)
        {
            count++;

            if (N <= 1)
                return N;
            if (dict.ContainsKey(N) == false)
                dict[N] = Fibonacci2(N - 1) + Fibonacci2(N - 2);
            return dict[N];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            count = 0;
            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            s.Start();
            this.textBox1.Text = Fibonacci1(long.Parse(this.textBox3.Text)).ToString();
            this.textBox2.Text = s.ElapsedMilliseconds.ToString() + " / " + count.ToString();
            s.Stop();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            dict.Clear();
            count = 0;
            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            s.Start();
            this.textBox1.Text = Fibonacci2(long.Parse(this.textBox3.Text)).ToString();
            this.textBox2.Text = s.ElapsedMilliseconds.ToString() + " / " + count.ToString();
            s.Stop();
        }

posted @ 2013-01-31 14:23  81  阅读(565)  评论(0编辑  收藏  举报