SoFunction
Updated on 2025-03-01

C# algorithm about the problem of giving birth to a calves

This article describes the problem of C# algorithm about the birth of a ox. Share it for your reference. The specific analysis is as follows:

question:

A newborn calf will give birth to one calf four years later and one every year from now on. There is a newborn calf. How many cattle will there be in total in 20 years?

At first I thought recursion was better. I thought about it for a long time, but I didn't think it out. So I thought of the following method to implement it, and the i-th data represents the age of the cow. The value of the array i indicates how many cows there are this year.

The implementation code is as follows:

const int YEAR = 50;

static void Main(string[] args)
{
  int[] yearAmount = new int[YEAR];
  yearAmount[0] = 1;
  for (int year = 1; year < YEAR; year++)
  {
 int count = 0;
 for (int i = year; i > 0; i--)
 {
   if (i >= 2)
 count += yearAmount[i]; //How many calfs can be born
   yearAmount[i] = yearAmount[i - 1]; //The age of the cow +1 }
 yearAmount[0] = count; //The calves were 0 years old  }

  int result = ();
  ("{0}Year Total:{1}A cow", YEAR, result);
  ();
}

The speed is quite fast!

I hope this article will be helpful to everyone's C# programming.