C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少

所属分类: 软件编程 / C#教程 阅读数: 59
收藏 0 赞 0 分享

方法一:递归算法

/// <summary>
/// 一列数的规则如下: 1、1、2、3、5、8、13、21、34求第30位数是多少, 用递归算法实现。(C#语言)
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public int GetNumberAtPos(int pos)
{
  if(pos==0||pos==1)
  {
    return 1;
  }
  int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2);
  return res;
}

方法二:不用递归

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Test
{
  public class Class1
  {
    private ArrayList list = new ArrayList();

    public Class1()
    {
    }

    public Class1(int num)
      : base()
    {
      int i;

      for (i = 1; i <= num; i++)
      {
        list.Add(Calculation(i));
      }
    }

    private int Calculation(int num)
    {
      if (num == 1 || num == 2)
        return 1;
      else
        return Convert.ToInt32(list[num - 2]) + Convert.ToInt32(list[num - 3]);
    }

    public int Calculation()
    {
      return Convert.ToInt32(list[list.Count - 1]);
    }
  }

  public class test
  {
    public static void Main()
    {
      int j;
      int num;
      for (j = 1; j < 100; j++)
      {
        Console.WriteLine("你要计算第多少位:");
        string readstr;
        readstr = Console.ReadLine();
        if (!string.IsNullOrEmpty(readstr))
        {
          if (int.TryParse(readstr, out num))
          {
            if (num < 1)
              continue;
            else
            {
              Class1 c1 = new Class1(num);
              Console.WriteLine(c1.Calculation());
            }
          }
          else
          {
            continue;
          }
        }
        else
        {
          break;
        }
      }
    }
  }
}

方法三:用循环实现

public long getNumber(int pos)
{
  long one = 1;
  long two = 1;
  if (pos == 0 || pos == 1)
  {
    return 1;
  }
  int i = 3;
  long sum = 1;
  while (i <= pos)
  {
    sum = one + two;
    one = two;
    two = sum;
    i++;
  }
  return sum;
}

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

C# SendInput 模拟鼠标操作的实现方法

C# SendInput 模拟鼠标操作的实现方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中 paint()与Onpaint()的区别

paint是事件onpaint方法onpaint方法是调用paint事件的,用哪一个,效果是一样,就看那一个方便了内部是这样实现的:
收藏 0 赞 0 分享

c#中GetType()与Typeof()的区别

c#中GetType()与Typeof()的区别,需要的朋友可以参考一下
收藏 0 赞 0 分享

将字符串转换成System.Drawing.Color类型的方法

将字符串转换成System.Drawing.Color类型的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C# 抓取网页内容的方法

C# 抓取网页内容的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于C#后台调用跨域MVC服务及带Cookie验证的实现

本篇文章介绍了,基于C#后台调用跨域MVC服务及带Cookie验证的实现。需要的朋友参考下
收藏 0 赞 0 分享

使用C#获取远程图片 Form用户名与密码Authorization认证的实现

本篇文章介绍了,使用C#获取远程图片 Form用户名与密码Authorization认证的实现。需要的朋友参考下
收藏 0 赞 0 分享

Winform跨线程操作的简单方法

线程间操作无效:从不是创建控件“label1”的线程访问它
收藏 0 赞 0 分享

C# WINFORM 强制让窗体获得焦点的方法代码

C# WINFORM 强制让窗体获得焦点的方法代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中方括号[]的语法及作用介绍

C#中方括号[]可用于数组,索引、属性,更重要的是用于外部DLL类库的引用。
收藏 0 赞 0 分享
查看更多