斐波那契数列的三种方法 兔子数列 C#

  1. 方法一,递归的代码简单,但是效率很低,很讨厌在计算机里面用递归。
  2. 方法二,等于一种查表的方式,推荐。
  3. 方法三,要记得通项公式,相比于第二点,更快,但是数比较大的时候,方次运算容易溢出,需要设计独特的方法表示大数。

以下图片,中间的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;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值