java算法:古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第四 个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

题目:古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

分析:兔子的规律的数列为1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

代码为:

public class exp1 {
public static void main(String[] args){
	int i=0;
	for(i=1;i<=20;i++)
		System.out.println(f(i));
}
public static int f(int x){
	if(x==1||x==2)
		return 1;
	else
		return f(x-1)+f(x-2);
}
}

或者:

public class exp1{
public static void main(String args[]){
	int i=0;
	math mymath = new math();
	for(i=1;i<=20;i++)
		System.out.println(mymath.f(i));
	}
}
class math{
	public int f(int x){
		if(x==1 || x==2)
			return 1;
		else
			return f(x-1)+f(x-2);
		}
	}

猜你喜欢

转载自blog.csdn.net/Markin2333/article/details/81568683
今日推荐