C is implemented by recursive algorithm: the rules of a column number are as follows: 1 1 2 3 5 8 13 21 34 and what is the 30th digit

  • 2021-10-15 11:21:18
  • OfStack

Method 1: Recursive algorithm


/// <summary>
/// 1 The rules for the number of columns are as follows : 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 Seek the first place 30 What are the digits,   It is realized by recursive algorithm. (C# Language )
/// </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;
}

Method 2: No recursion


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(" How many digits do you want to count :");
        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;
        }
      }
    }
  }
}

Method 3: Implement it with a loop


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


Related articles: