题目描述
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
输入描述:
输入int型表示month
输出描述:
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
输入描述:
输入int型表示month
输出描述:
输出兔子总数int型
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int month = scanner.nextInt();
System.out.println(count(month));
}
}
public static int count(int month)
{
if (month == 1 || month == 2)
return 1;
return count(month - 1) + count(month - 2);
}
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int month = scanner.nextInt();
System.out.println(count(month));
}
}
public static int count(int month)
{
if (month == 1 || month == 2)
return 1;
int old = 1;
int young = 1;
int month1 = 1;
int month2 = 0;
for (int i = 4; i <= month; i++)
{
old += month2;
month2 = month1;
month1 = old;
young = month1 + month2;
}
return young + old;
}
}