SoFunction
Updated on 2025-03-06

C# uses recursive algorithm to implement: the rules of a column number are as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34, find the 30th digit number

Method 1: Recursive Algorithm

/// <summary>
/// The rules for a column of numbers are as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34 Find the 30th digit number and use a recursive algorithm to implement it.  (C#language)/// </summary>/// &lt;param name="pos"&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public int GetNumberAtPos(int pos)
{
  if(pos==0||pos==1)
  {
    return 1;
  }
  int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2);
  return res;
}

Method 2: No recursion

using System;
using ;
using ;
using ;

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

    public Class1()
    {
    }

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

      for (i = 1; i &lt;= num; i++)
      {
        (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[ - 1]);
    }
  }

  public class test
  {
    public static void Main()
    {
      int j;
      int num;
      for (j = 1; j &lt; 100; j++)
      {
        ("You want to calculate the number of digits:");
        string readstr;
        readstr = ();
        if (!(readstr))
        {
          if ((readstr, out num))
          {
            if (num &lt; 1)
              continue;
            else
            {
              Class1 c1 = new Class1(num);
              (());
            }
          }
          else
          {
            continue;
          }
        }
        else
        {
          break;
        }
      }
    }
  }
}

Method 3: Implementation with loops

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;
}

The above is the entire content of this article. I hope you can give you a reference and I hope you can support me more.