The story of the cow There was a cow who gave birth to a heifer every year, and each heifer gave birth to a heifer at the beginning of each year from the fourth year onwards, then in the twentieth year

Topic: There is a cow that gives birth to a heifer every year. From the fourth year onwards, each heifer also gives birth to a heifer at the beginning of each year. Then in the 20th year

Number of Cows vs Year
years 1 2 3 4

5

6 7
quantity 1 2 3 4 6 9 13

Let's first look at how to solve it manually: there is one cow in the first year, and one in the second year, and so on, we can get a list manually: m(n) in the column of cow individuals represents a cow whose age is n years Cows have m heads. From this list we can see that f4 = f1 + f3 = 4; f5 = f2 + f4 = 6; f6 = f3 + f5 = 9; f7 = f4 + f6 = 13; : This is a deformation of the Fibonacci sequence, which can be solved by an iterative method or by a recursive function

learn from

In the fifth year, one calf produced in the second year started to produce, so there are 6 cows, in the sixth year, the second year calf is producing one cow, and in the third year, two calf cows are producing 2 calf, so there are 9 cows in total. Therefore, it can be seen from the table that the number of cows begins to be regular from the fifth year, F(n) = F(n-1)+F(n-3), that is, the number of cows in the current year is the number of cows in the previous year Plus the number of cows in the previous three years

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  int n;
  while((n=in.nextInt())!=0){
  if(n>=1&&n<=4)
  System.out.println(n);
  else if(n>4){
  System.out.println(Fun(n));
}
}
}
  public static int Fun(int m){
    if(m==1)
      return 1;
    else if(m==2)
      return 2;
    else if(m==3)
      return 3;
    else if(m==4)
      return 4;
    else
      return Fun(m-1)+Fun(m-3);
}
}

Guess you like

Origin blog.csdn.net/qq_28821897/article/details/129927239