Huawei OD machine test - count the total number of rabbits every month (C++ & Java & JS & Python)

describe

There is a kind of rabbit that will give birth to a rabbit every month from the third month after birth, and the little rabbit will give birth to another rabbit every month after the third month.

Example: Suppose a rabbit is born in the 3rd month, then it will give birth to a rabbit every month from the 5th month.

There is a rabbit in January. If the rabbits are not dead, what is the total number of rabbits in the nth month?

Data range: input satisfies 1≤�≤31 1≤n≤31 

Enter a description:

Enter an int integer to represent the nth month

Output description:

Output the corresponding total number of rabbits

Example 1

enter:

3

output:

2

Java:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            int n = sc.nextInt();
            System.out.println(f(n));
        }
    }
    public static int f(int n){
        if(n == 1 || n == 2){
            return 1;
        }
        return  f(n-1)+f(n-2);
    }
}

python:

n = int(input())

a = 1    # 出生不短于两个月的兔子

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/132716799